2012-02-09 62 views
3

我的應用程序由於N + 1個查詢而變慢。我在Rails 3.1和Oracle 11.2中使用了will_paginate gem。如何避免使用will_paginate進行N + 1查詢?

通常情況下,解決方案是使用ActiveRecord#includes()在讀取父記錄的同時讀取子記錄,但我所做的每一次嘗試似乎都不適用於will_paginate或結束將整個數據庫提取到內存中。我嘗試製作一個命名作用域,但似乎在調用時會立即提取作用域,而不是延遲。

class Parent < ActiveRecord::Base 
    has_many :children, :dependent => :delete_all 
end 

class Child < ActiveRecord::Base 
    belongs_to :parent 
end 

class ParentsController < ApplicationController 
def index 
    @parents = Parent.paginate page: params[:page], order: 'id', per_page: 32 
end 

Index.html.erb包含,除其他事項外,

<%= page_entries_info @parents %> 
<%= will_paginate @parents, :container => false %> 
<% @parents.each do |parent| %> 
<%= parent.call_to_method_that_uses_children_association_causing_N+1_query %> 
<% end %> 

如果我不能來獲取整個數據庫到內存中,並沒有想獲取父母的頁面,其次是N次子提取,除了放棄will_paginate之外還有其他選擇嗎?

另外,是否有任何will_paginate的實質性文檔? github上的信息非常稀少。例如,will_paginate方法的container選項是什麼意思?

回答

7
Parent.includes(:children).paginate(:page => params[:page], :per_page => 30) 

From another question that is similar to yours

+0

謝謝,我想張貼提取了整個數據庫,Parent.find之前類似的東西(:所有).includes(:兒童).paginate(...)。沒有意識到find()調用是不需要的。再次感謝。 – 2012-02-09 21:49:38