这个问题涉及清理 View 并为 Controller 提供更多工作。
在我的项目中有很多情况,我的 View 中显示了嵌套变量。例如:
# controller
@customers = Customer.find_all_by_active(true)
render :layout => 'forms'
# view
<% @customers.each do |c| %>
<%= c.name %>
<% @orders = c.orders %> # I often end up defining nested variables inside the view
<% @orders.each do |o| %>
...
<% end %>
<% end %>
我对 RoR 相当陌生,但似乎我在这里所做的事情与“智能 Controller ,愚蠢的 View ”的心态相矛盾。如果我有很多客户,每个客户都有很多订单,我如何在 Controller 中正确定义这些变量,然后在 View 中访问它们?
如果您可以提供一个示例来说明 Controller 的外观以及我如何在 View 中与该 Controller 相关联,那么这将非常有帮助。非常感谢!
最佳答案
我不认为你所做的事情有什么严重错误。循环访问客户并输出他们的一些属性,对于每个客户,循环访问他们的订单并输出一些属性是一个非常面向 View 的操作。
在 MVC 架构中, Controller 负责与模型交互、选择 View 以及(当然在 Rails 的情况下)为 View 提供渲染模型所需的信息。
如果您多次重复该确切代码,您可能会考虑将代码提取到 View 助手中。您甚至可以将其泛化,传入模型和关联的名称。我还没有测试过,但你应该能够做这样的事情:
def display_attributes(models, association, attribute, association_attribute)
content = ''
models.each do |m|
content << "<p>#{m.attribute}</p>"
associated_models = m.association
associated_models.each do |am|
content << "<p>#{am.association_attribute}</p>"
end
end
content
end
然后在 View 中,您可以像这样使用帮助器:
<%= display_attributes(@customers, orders, name, name) %>
显然,您可以更改帮助器方法中的 HTML 标记以满足您的要求。请注意,如果您不使用 Rails 3,那么您将需要转义辅助方法中属性名称的输出。
关于ruby-on-rails - 如何让 View 更简单, Controller 更有用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3144056/