在rails中使用每个代码块

时间:2013-01-29 17:46:45

标签: ruby-on-rails block each

我有这样的动作来添加一个ContestEntry记录来展示。

@entry = ContestEntry.find(params[:content_id])
if @entry.view_in_showcase == true
  @entry.view_in_showcase = false
  @entry.save
  redirect_to :back, :notice => "Drop design to showcase"
else
  @entry.view_in_showcase = true
  @entry.save
  redirect_to :back, :notice => "Add design to showcase"
end

但是现在我必须为多个记录实现它,并且我有包含ContestEntry记录的数组。如何将这个数组与这些代码一起使用?

例如:

arr_showcase = [ContestEntry.first,ContestEntry.last,..]

如何以与文本相同的目的更新此数组。

2 个答案:

答案 0 :(得分:1)

假设您的数组是@entries

@entries.each {|e| e.update_attribute('view_in_showcase', false) if e.view_in_showcase } 

答案 1 :(得分:1)

重用此代码的第一步是在方法中重构它。

class ContestEntry
  def toggle_view_on_showcase!
    view_on_showcase.toggle!
    save
    view_on_showcase
  end
end

# Refactor controller
if @entry.toggle_view_on_showcase!
  redirect_to :back, :notice => "Add design to showcase"
else
  redirect_to :back, :notice => "Drop design to showcase"
end

# reuse!
arr_showcase.each { |e| e.toggle_view_on_showcase! }