Thursday, November 5, 2009

Pagination gem for Ruby on Rails

For ruby on rails there is a gem available for pagination called will_paginate to provide pagination to the database results. Process to install this gem to your application.
1. rake gems:install
2. gem sources -a
3. gem install mislav-will_paginate
For the first time to install gems package run step 1. If you already run this command no need to run again. step 2 is to append the gems to your rails. Step 3 will install the will_paginate gem to your application.

After installed gem successfully follow the below steps to enable pagination to your models.

1. In your config\environment.rb file add do |config|
config.gem 'mislav-will_paginate', :version => '~> 2.2.3', :lib => 'will_paginate', :source => ''

2. rake gems:install

3. In your model, mention how many records display per page

def self.per_page

4. In your controller, replace
@yourmodels = Yourmodel.find
@yourmodels = Yourmodel.paginate :page => params[:page], :order => 'created_at DESC'
5. In your index view, add below to see the pagination
<%= will_paginate @models %>

see http://localhost:3000/models