Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
  • Kaminari gem implementation in Rails

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 793
    Comment on it

    Kaminari is a very popular pagination gem for Rials . It's a Scope & Engine based, clean, powerful, customizable and sophisticated paginator gem which uses scopes to flow nicely with Active Record queries.

    Features of Kaminari:


    Kaminari does not globally pollute Array, Hash, Object or AR::Base.


    Easy to use
    Just install the gem and our models are ready to be paginated. There is no configuration required and  don't have to define anything in our models or helpers.


    Simple scope-based API
    Its support method chainable like Rails way and we can make a chainable link in different other conditions before or after the paginator scope.


    Customizable engine-based I18n-aware helper

    We can define the pagination helper as a repository of links & non-links. The job of Kaminari is to render each of them via its own  partial inside the Engine. Thus, overriding partial templates to change or override their behaviour becomes a walk in park.  
    Kaminari offers support for multiple ORMs, including ActiveRecord, DataMapper, Mongoid, MongoMapper multiple web frameworks including Rails and multiple engines for i.e. ERB, Haml.

    Install Kaminari gem

    Add into Gemfile

    gem 'kaminari'


    bundle install

    Generate Model and controller for listing posts

    rails generate scaffold User title:string email:string body:string

    Then run

    rake db:migrate

    Change route

    Rails.application.routes.draw do
      root to: "posts#index"
    Now modify Posts controller 
    class PostsController < ApplicationController
      def index
        @posts =[:page]).per(10)


    With the help of the page method, it is very easy to figure out the page you are on. The per method, on the other hand, lets kaminari know how many items you are looking forward to have per page.


    Now open posts index page and modify as following

    <hr />
    <% @posts.each do |post| %>
      <h2><%= post.title %></h2>
      <%= post.body %>
    <% end %>
    <hr />
    <%= paginate @posts %>
    <%= page_entries_info @posts %>


    paginate: This a helper and responsible for rendering the pagination links.
    page_entries_info: This helper displays a line similar to Displaying posts 1 - 10 of 100 in total.

    This can be  helpful in letting the user know how many items there are in the list.

 0 Comment(s)

Sign In

Sign up using

Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: