Sunday, November 2, 2008

Using will_paginate for pagination

Since Rails 2.0 the pagination has been removed from the core rails. This allows more flexibility in the choice of the pagination method you want to use.

One secure choice is will_paginate. It is available as a gem

To install the will_paginate gem follow the procedure :

1. rake gems:install
2. gem sources -a http://gems.github.com
3. gem install mislav-will_paginate

The usage of this gem in a project is simple :

1. In your config\environment.rb file add

Rails::initializer.run do |config|
config.gem 'mislav-will_paginate', :version => '~> 2.2.3', :lib => 'will_paginate', :source => 'http://gems.github.com'
end


2. rake gems:install

3. In your controller, replace

@yourmodels = Yourmodel.find

with

@yourmodels = Yourmodel.paginate :page => params[:page], :order => 'created_at DESC'

4. In your index view, add

<%= will_paginate @yourmodels %>

Note : a trick, if it tells you it does not find the method in the controller, configure the gem directly in config\development, test or production file.