简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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