I'm using acts_as_category plugin to manage my categories logic. In almost every page of the site the categories and sub-categories tree is shown:
<div id="categories_">
<% Category.roots.each do |category| %>
<h3><%= 开发者_JS百科category.name %></h3>
<div>
<ul class="subcat">
<% category.children.each do |subcategory| %>
<li><%= link_to subcategory.name, "/category/#{subcategory.to_param}" %></li>
<% end %>
</ul>
</div>
<% end %>
</div>
It produces a lot of SQL queries shown in the log file, is there a way to fetch multiple rows in a single query?
EDIT:
I tried rewriting the roots scope in Category model with the same results:
named_scope :roots,
:conditions => ["((hidden IS NULL OR hidden = 0) AND (parent_id IS NULL))"],
:include => :children
EDIT:
It seems that the problem is with the plugin, and the author explained here (http://goo.gl/MwRSJ) why it can't be changed. Any other suggestion for managing my Categories?. I've used acts_as_tree but it seem a bit outdated. Thanks!.
What you're seeing is the N+1 query problem which is solved by eager loading associations.
<% Category.roots(:include => :children).each do |category| %>
精彩评论