0

我有这样的动作来添加一个 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,..]

如何在文本上方以相同目的更新此数组。

4

2 回答 2

1

假设您的数组是@entries

@entries.each {|e| e.update_attribute('view_in_showcase', false) if e.view_in_showcase } 
于 2013-01-29T17:53:48.163 回答
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! }
于 2013-01-29T17:55:52.590 回答