简体   繁体   English

Ruby on Rails-从视图到模型重构ActiveRecord查询

[英]Ruby on Rails - Refactoring ActiveRecord queries from the view to the model

I am aware of the advice "fat models / skinny controllers" and "never put logic in the view"; 我知道“胖模型/瘦控制器”和“从不看逻辑”的建议; however, it would help me to learn from an example. 但是,这将有助于我学习一个示例。 In the following, what is the best way to rewrite the code so that the query is not in the view? 在下面,重写代码以使查询不在视图中的最佳方法是什么?

Model 模型

 class Product < ActiveRecord::Base
   belongs_to :order
 end

 class Order < ActiveRecord::Base
   has_many :products
 end

Controller 控制者

 @orders = Order.all

View 视图

 <% @orders.each do |o| %>
 <%= Product.where("order_id = ?", o.id).count %>
 <% end %>

It depends on exactly what you want to display, but the straightforward option is to take advantage of the associations you've specified: 这取决于您要显示的内容,但是直接的选择是利用您指定的关联:

<% @orders.each do |o| %>
  <%= o.products.count %>
<% end %>

Then in your controller, you can use eager loading to optimize your SQL calls. 然后,在控制器中,您可以使用紧急加载来优化SQL调用。

@orders = Order.all(:include => :products)

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

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