这是可怕的代码,我知道。当它基于集合中的每个记录时,如何将其移动到模型中?
<% @brands.each do |b| %>
<% booleans = Preference.columns.select { |c| c.type == :boolean }.map(&:name) %>
<% trues = booleans.select { |name| b.preference.send(name) == true } %>
<%= trues.to_sentence.humanize %>
<% end %>
答案 0 :(得分:1)
将逻辑放入模型中:
# app/models/brand.rb
def self.trues
self.all.each do |b| # OR whatever collection you're trying to iterate through
booleans = Preference.columns.select {|c| c.type == :boolean}.map(&:name)
trues = booleans.select {|name| b.preference.send(name) == true}
return trues
end
end
然后,在视图中显示返回的值:
# view
<%= Brand.trues.to_sentence.humanize %>
作为惯例,您可能希望将模型便捷方法存储到控制器中的实例变量,然后在视图中呈现实例变量:
# controller action
@trues = Brand.trues
# view
<%= trues.to_sentence.humanize %>