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.

About these ads

6 thoughts on “Paginating multiple models using will_paginate on the same page

  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.

Leave a Reply

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

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 )

Google+ photo

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

Connecting to %s