will paginate with multiple tables
I have following tables :
- users
- accounts ( user has_one account )
- 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
开发者_如何学Go it should fetch it from the variable and not execute a query.
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)
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)
精彩评论