will paginate with multiple tables

浪子不回头ぞ 提交于 2019-12-08 09:12:40

问题


I have following tables :

  1. users
  2. accounts ( user has_one account )
  3. pictures ( user has_many pictures )

I want to display a User along with its related account and pictures. This is a typical N+1 queries problem and I solved it using eager loading.

User.includes(:account, :pictures).all

I am trying to use will_paginate gem. How do I include this eager loading mechanism into will_paginate ?

I found a similar question here: Using will_paginate with multiple models (Rails). But the links in the answer are out of place and the answer itself is quite old. Furthermore, it uses raw sql queries, which I don't prefer.

I want the output as follows :

user.name account.field1 account.field2 picture.count
abc1       abcf1          abcf2           4
zxc        zxcf1          zxcf2           7

So basically when I do user.name , it will not execute a query but just get the data from the variables; same way when I do user.account.field1 it should fetch it from the variable and not execute a query.


回答1:


The paginate method is similar to all method. So you can simply do this:

User.includes(:account, :pictures).paginate(
  :page => params[:page], :per_page => 30)

OR

User.paginate(:include=> [:account, :pictures], 
  :page => params[:page], :per_page => 30)

Note:

The will_paginate gem provides a convenience method on the Array class for pagination:

[1,2,3,4].paginate(:page => 1, :per_page=>2)



回答2:


I finally used pagination on a array rather than the gem itself.

    current_page = Integer(params[:page]||1)
    per_page = 250
    @users_r = User.all(:conditions=>"some condition",:limit=>per_page,:offset=>per_page*(current_page-1),:include=>[:account,:user_info ,:pictures])
    count = @users_r.length
    @users = WillPaginate::Collection.create(current_page, per_page, count) do |user|
      user.replace(@users_r)
    end
    @users.paginate(params)


来源:https://stackoverflow.com/questions/7315361/will-paginate-with-multiple-tables

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!