6.1. Adding Pagination

As seen before, when you visit / or /articles all the currently published posts are shown. If you are a regular blogger you'll probably post at least an article each week. At that pace, the front page would soon become an exceedingly long scroll of content. To work around this issue, you are going to add pagination, which is the ability to define a set number of articles that will appear per page. Here it is assumed that you want to display only the latest post on the homepage.

You could implement this feature yourself, given that ActiveRecord's finders allow you to specify :limit and :offset conditions for SELECT queries, but why should you reinvent the wheel? Pagination is an extremely common requirement for Web applications, and several plugins are available that can be readily used.

In earlier versions of Rails, pagination was a feature that was included by the framework, but its implementation and performance were less than satisfactory, so it has since been removed.

6.1.1. Installing the will_paginate Plugin

The most commonly used pagination plugin is will_paginate. This excellent plugin makes adding pagination to your applications a joy. The recommended way of installing it is through RubyGems. The first thing that you need to do, then, is to add a requirement for the gem in config\environment.rb.

Add to that file the following line:

config.gem 'mislav-will_paginate', :version => '>= 2.3.2', :lib => 'will_paginate', :source => 'http://gems.github.com' ...

Get Ruby on Rails® for Microsoft Developers 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.