在我看来,我有一个复杂的循环,它创建了 500 个 SQL 查询(以获取 500 本书的信息)。如何通过在控制器中加载变量来避免大量 SQL 查询?
我当前的(伪)代码:
控制器索引操作:
@books = Book.scoped.where(:client_id => @client.id).text_search(params[:query])
@feature_root = Book.multiple_summary_details_by_category( @books )
#...returns a hash of books
@features = @feature_root.to_a.paginate(:page => params[:page], :per_page => 4)
index.html.haml
= render :partial => "feature", :locals => { :features => @features }
_features.html.haml
- features.each_with_index do |(cat_name, array_of_books), i|
%h2
= cat_name
- array_of_books[0..10].each do |feature|
= link_to image_tag(feature[:cover], :class => "product_image_tiny"), book_path(feature[:book])
# more code
- array_of_books.sort_by{ |k, v| k["Author"] }.each do |feature|
- feature.each do |heading,value|
%span.summary_title
= heading + ':'
%span.summary_value
= value