ruby-on-rails – 如何使用will_paginate避免N 1个查询?

我的应用程序因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选项是什么意思?

解决方法

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

From another question that is similar to yours

相关文章

validates:conclusion,:presence=>true,:inclusion=>{...
一、redis集群搭建redis3.0以前,提供了Sentinel工具来监控各...
分享一下我老师大神的人工智能教程。零基础!通俗易懂!风趣...
上一篇博文 ruby传参之引用类型 里边定义了一个方法名 mo...
一编程与编程语言 什么是编程语言? 能够被计算机所识别的表...
Ruby类和对象Ruby是一种完美的面向对象编程语言。面向对象编...