Introduction

The will_paginate gem has long since been the most popular gem used when it comes to pagination. However it is not the only gem out there. Kaminari is another very popular pagination gem. In this article we will show you how to use it in your application. Let's get started.

Rails Application Setup

To begin using the kaminari gem, we must first add it to our gemfile. Open up your gemfile and add in the line listed below.

Gemfile:

gem 'kaminari', '~> 0.16.1'

Now run a bundle install to install the gem.

Terminal Commands:

bundle install

Next, let's create a model called Post. The post model in this example will represent a blog post. Run the commands below to create the post model now.

Terminal Commands:

rails g model Post title body:string
rake db:migrate

Great, we need some seed data. Open your db/seeds.rb file and modify it so that it looks like the code listed below.

db/seeds.rb:

(1..100).each do |i|
  Post.create!(title: "Lipsum Post #{i}", body: %{
      Nullam hendrerit iaculis sodales. Curabitur varius nibh arcu, id molestie nibh fermentum vitae. Cras quis semper dui. Cras porttitor urna sit amet risus vehicula tempor. Maecenas quis tempor ligula. Donec et nibh eu leo volutpat placerat. Fusce vulputate elit in nisi pretium, vel fermentum mi fermentum. Mauris scelerisque, lectus non luctus ultricies, urna eros tincidunt risus, at varius sapien diam id erat.
  })
end

Now run a rake db:seed to add the seed data.

Terminal Commands:

rake db:seed

Great, now we need to add a controller called Posts that we will use to render the posts. Run the command below to create this controller now.

app/controllers/posts_controller.rb:

rails g controller Posts index

Now let's modify our routes file to set a site root. Open up your config/routes.rb file and modify it so that it looks like the code listed below.

config/routes.rb:

Rails.application.routes.draw do
  root to: "posts#index"
end

Great, now open up your Posts controller and modify it so that it looks like the code listed below.

app/controllers/posts_controller.rb:

class PostsController < ApplicationController
  def index
    @posts = Post.page(params[:page]).per(10)
  end
end

As you can see, the first bit of our pagination code is here. The page method tells kaminari what page we are on. The per method tells kaminari how many items we wish to have per page.

Now let's open up the index view for our Posts controller and modify it so that it looks like the code listed below.

app/views/posts/index.html.erb:

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

The paginate helper is the line actually responsible for rendering the pagination links. The page_entries_info helper displays a line similar to Displaying posts 1 - 10 of 100 in total. This can be extremely helpful in letting the user know how many items there are in the list.

Global Configuration

You can also specify global defaults for Kaminari. First, run the following command to generate an initializer file for Kaminari.

Terminal Commands:

rails g kaminari:config

If you open up the config/initializers/kaminari_config.rb file you'll see something similar to the following:

config/initializers/kaminari_config.rb:

Kaminari.configure do |config|
  # config.default_per_page = 25
  # config.max_per_page = nil
  # config.window = 4
  # config.outer_window = 0
  # config.left = 0
  # config.right = 0
  # config.page_method_name = :page
  # config.param_name = :page
end

A description of these options can be found below.

config.default_per_page Specifies the default amount of items to display per page.
config.max_per_page The maximum amount of items to display per page.
config.window Specifies the inner window size. The inner window is the number of items in the middle of the pagination block. e.g. « First ‹ Prev ... 1 2 3 4 ... Next › Last », in the previous example, 1 2 3 4 would be considered the inner window.
config.outer_window Specifies how many items to display in the outer window. For example: 1 2 3 4 ... 8 9 10 11, numbers visible on the outside are the outer window.
config.left Specifies how many items should be displayed in the left outer window.
config.right Specifies how many items should be displayed in the right outer window.
config.page_method_name Changes the page method name from page to whatever you want. Can be used to avoid conflict with other gems that use page.
config.param_name The default parameter to use when looking for the page number.

I18N

Kaminari can be configured via I18N. The default I18N configuration file looks like the code listed below.


en:
  views:
    pagination:
      first: "&laquo; First"
      last: "Last &raquo;"
      previous: "&lsaquo; Prev"
      next: "Next &rsaquo;"
      truncate: "&hellip;"
  helpers:
    page_entries_info:
      one_page:
        display_entries:
          zero: "No %{entry_name} found"
          one: "Displaying <b>1</b> %{entry_name}"
          other: "Displaying <b>all %{count}</b> %{entry_name}"
      more_pages:
        display_entries: "Displaying %{entry_name} <b>%{first}&nbsp;-&nbsp;%{last}</b> of <b>%{total}</b> in total"

To override it, simply modify your locale files under config/locales.

Additional information on the Kaminari gem can be found at https://github.com/amatsuda/kaminari. That's it! Thanks for reading!