I have two models, with those associations:
class Product < ActiveRecord::Base
has_many :side_orders
has_many :garnishes, :through => :side_orders
attr_accessible :garnishes_number
end
Garnishes are also products, so it’s a self-joined association:
class SideOrder < ActiveRecord::Base
belongs_to :product
belongs_to :garnish, :class_name => "Product", :foreign_key => "garnish_id"
attr_accessible :list_number
end
One product may have many lists of garnishes (so that customer may choose different garnishes when they order one product). It’s one list per choice. One product don’t have more than “garnishes_number” lists of choices.
In my application, in the admin part, I have to do something like this:
<% Product.all.each do |product| %>
<% for i in 0..(product.garnishes_number - 1) %>
Lists of garnishes:
<%= product.garnishes.where("side_orders.list_number = ?", i) %> <br />
<% end %>
<% end %>
It’s just an example… Problem is that Rails do one query per value of “i”, so if a product has 8 lists, Rails will perform 8 queries to the database… And when there are more than hundreds of products, it becomes really slow…
Is there a way to optimize such a query? Includes doesn’t seem to work… If anyone has any idea or maybe a different logic, don’t hesitate to answer.
[Edit] The fact that I want to access each list of garnishes is important because I want them to appear in a table in such way:
<table>
<thead>
<td>Product</td>
<td>List of garnishes </td>
</thead>
<tbody>
<% Product.all.each do |product| %>
<% for i in 0..(product.garnishes_number - 1) %>
<tr>
<td>product.name</td>
<td>
List number <%= i %>:
<%= product.garnishes.where("side_orders.list_number = ?", i) %>
</td>
</tr>
<% end %>
<% end %>
</tbody>
</table>
I didn’t put that in the first place, because I didn’t want my question to be too long… But, I think I should have wrote it down already so that my problem could be more understandable… Sorry ^^’
Thanks a lot!
Kulgar.
you can do it by following way
This will call where query only one time for each product