Add Pagination in Rails

This tip shows how to add pagination in Rails.

Let’s create a basic rails project :

$rails new pagination   #creating project

$cd pagination  
$rails generate scaffold user name:string address:string
#Createed a basic app with 2 fields name & Address
$rake db:migrate
#let's create our users table in Database.

Now run your rails server & Navigate to  localhost:3000/users/new Here keep adding 10+ users to our application.

Now navigate to localhost:users/index and notice all added users are listed.

How about making only 5 users visible per page??? Let’s use our will_paginate gem and make only 5 users visbile to our View.

Step 1 : Open your Gemfile and add will_paginate gem to Gemfile.
gem “will_paginate”

Step 2 : Go with $ bundle install in CMD/Terminal.

Step 3 : Now open your controller file(users_controller.rb) and check index action.

Replace   "@users = User.all " with following lines :
@users  = User.paginate(:page => params[:page], :per_page=>5)

Step 4 :
Open your index.html.erb file and add this to rendering loop.

  
                   
                                  
                              
                          
    

Now just refresh your localhost:3000/users/index and notice 5 users are visible per Page with nice navigation links to land on any specific page as well as traverse Prev/Next

150 150 Burnignorance | Where Minds Meet And Sparks Fly!