简体   繁体   English

在rails中使用每个代码块

[英]using each with code block in rails

I have action like this to add one ContestEntry record to showcase. 我有这样的动作来添加一个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

But now I have to implement it for multiple records and I have array that includes ContestEntry records.How can I use this array with these code ? 但现在我必须为多个记录实现它,并且我有包含ContestEntry记录的数组。如何将这个数组与这些代码一起使用?

for instance : 例如 :

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

How can update this array with same purpose above the text. 如何更新此数组与文本上方的目的相同。

假设你的数组是@entries

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

First step to reuse this code is to refactor it inside a method. 重用此代码的第一步是在方法内部重构它。

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! }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM