【问题标题】:Rails: view loop refactoringRails:视图循环重构
【发布时间】:2014-02-19 02:23:40
【问题描述】:

这是可怕的代码,我知道。当它基于集合中的每条记录时,如何将其移动到模型中?

<% @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 %>

【问题讨论】:

  • 你想要完成什么?我很乐意提供帮助,但不是逆向工程
  • 这会返回一个关联列的列表,这些列是真的。
  • 抱歉,我想你会得到列表最后一个元素的结果,因为:trues = booleans.select { |name| b.preference.send(name) == true } 你不想使用“trues +=”吗?对不起,如果我错了。
  • 它肯定会返回一个列表。

标签: ruby-on-rails ruby-on-rails-3 erb


【解决方案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 %>

【讨论】:

  • 虽然我在您的解决方案中更改了一些内容,但这绝对让我走上了正确的道路。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-11-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-11-04
  • 2012-10-03
相关资源
最近更新 更多