5.4. Pagination

If you've used Google, you've seen pagination in action. The first 25 or so search hits are displayed, followed by some navigation to allow you to move between pages. On the back end, the server knows what page you are looking for and serves up the correct set of results for that page.

In the Rails 1.x days, pagination was a helper method and part of the Rails core. But it turned out that a lot of people didn't much care for the implementation, and the pagination helper was removed from Rails 2.0 as part of the general shedding of non-core functionality. There's no clear market leader in its place, but there are a couple of plugin contenders worth looking at. Keep an eye out for new developments in this space.

5.4.1. will_ paginate

The first contender is the will_paginate plugin available from the folks at Err Free consulting. You can get the plugin from here:

$ ruby script/plugin install svn://errtheblog.com/svn/plugins/will_paginate

This plugin allows you to use the paginate method in any place where you would use the method find(:all). Here is an example of the simplest use of this method:

@recipes = Recipe.paginate(:page => params[:page])

The page option tells the plugin which page of data to retrieve, and must be specified on each call to paginate. The default is to put 30 items on the page. If your class responds to a per_page class method, the results of that method are used, so you can specify that as follows:

def self.per_page
  10
end

Any options you send ...

Get Professional Ruby on Rails™ now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.