Tuesday, 19 April 2011

Kaminari : beautiful pagination gem for Rails 3

Pagination on ActiveRecord


Pagination
In older times, i used to use Will_Paginate , a very nice pagination gem. But after using Kaminari i find will_paginate little more verbose.
Nowadays i uses  a beautiful gem christened Kaminari by amatsuda

How to setup kaminari to paginate your table ?
INSTALLATION
open your gem file in your app folder . eg   myApp/Gemfile and add this gem:
.
.
gem 'kaminari'
.
.
Save it and run the command prompt
go into you app directory  and run :
$ bundle install
Now you're ready to use your kaminari pagination gem in your app.

USAGE
Let me take a simple example : " List all users in my database "

controller file name : app/controllers/users_controller.rb
class UsersController < ApplicationController
.
.
def show
          # to fetch all user from 'users' table via "User" model
         @users = User.where(:id>=0).order("id asc").page( params[:page]).per(5)
  end
.
.
end

Now , in view:  app/users/show.html.erb , just add a single line before your table listing:

<%= paginate @users %>
<% @users.each do |user| %>
<tr>
<td><%= link_to user.name, :action =>'show',:id =>user.id %></td>
<td><%=  user.username %></td>
<td><%= user.email %></td>
<td><%= link_to acceptance_status( user.accepted ), {:action => 'toggleAcceptance',:id=> user.id}  %></td>
<% if !session[:is_admin] %>
<td><%= link_to "show" ,{:action =>'show',:id =>user.id}, :class=>"icon_read_more_16x16" %></td>
<td><%= link_to "Edit" ,{:action =>'edit',:id =>user.id}, :class=>"icon_pen_16x16" %></td>
<td><%= link_to "destroy" ,{:action =>'destroy',:id =>user.id }, :class => "icon_x_14x14", :confirm =>"Are your sure?" %> </td>
<% end %>

</tr>
<% end %>


RESULT:




MORE CUSTOMIZATION


Kaminari  does provide additional scope besides `page` and `per`. 
`order' : To sort list(  Ascending order by default)
eg:
     @users = User.order("id asc").page(params[:page]).per(3)

To get users with a predicate say with email_id="sonukr666@gmail.com",  use rails `where' clause.
   @users = User.where(:email_id=>"sonukr666@gmail.com").order(:id).page(params[:page]).per(3).


Need More Help? 
watch episode 254 on railscast

Pagination on an Array


What if result is not from any model but an array??
Here PaginatableArray come into picture


Controller:

@all_result = ["a", "ab", "a", "a"];
@perPageResult = Kaminari::PaginatableArray.new( @all_result ).page(params[:page]).per(2)

now on view:
         <%= paginate @perPageResult %>
Was that tough?




No comments:

Post a Comment