diasks2
diasks2

Reputation: 2142

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

Upvotes: 0

Views: 668

Answers (1)

muffinista
muffinista

Reputation: 6736

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)

Upvotes: 3

Related Questions