如何使用will_paginate避免N + 1个查询?

时间:2012-02-09 17:42:10

标签: ruby-on-rails ruby-on-rails-3.1 will-paginate

我的应用程序因N + 1查询而变慢。我正在使用带有Rails 3.1和Oracle 11.2的will_paginate gem。

通常情况下,解决方案是使用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选项是什么意思?

1 个答案:

答案 0 :(得分:7)

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

From another question that is similar to yours

相关问题