Paginating multiple models using will_paginate on the same page

The will_paginate plugin makes pagination for your models in Ruby on Rails ridiculously simple. However sometimes you’ll find yourself wanting to paginate over two or more models on a single page. For instance, you might want to display a list of users and administrators on a single page along with a pager for each model (assuming that users and administrators are stored in separate tables).

Controller code

The code is pretty simple, except that I am specifying the page to show to be equal to params[:user_page] and params[:administrator_page] respectively. Since we are allowing the ability to page over two models, we need two separate parameters to determine which page of users or administrators to show.

@users = User.paginate(:page => params[:user_page], :per_page => 10)
@administrators = Administrator.paginate(:page => params[:administrator_page], :per_page => 10)

View code

In the view all we need to do is make sure to set the param_value to the correct value to indicate to the plugin that we want to use a different parameter name for the page. The default is simply called ‘page’, but we need to make sure to use ‘user_page’ and ‘administrator_page’ instead for the two different models.

<%= will_paginate @users, :param_name => 'user_page' %>
<%= will_paginate @administrators, :param_name => 'administrator_page' %>

That’s it, you should now be able to page through your users and administrators on the same page.

Advertisement

4 responses to this post.

  1. Hello,

    I am exactly looking for this type of concept only.

    I am dealing with 5 different types of tables. There i need to have 5 different will_pageinates.

    This article is very helpful to me.

    Reply

  2. Thanks so much I got for which I was searching

    Reply

  3. Posted by ranjeet on May 10, 2010 at 5:46 am

    hi,

    Thanks i am exactly looking for this..

    Reply

  4. Posted by pico farad on March 2, 2011 at 10:28 pm

    thanks

    Reply

Leave a Reply

Fill in your details below or click an icon to log in:

Gravatar
WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.