kaminari gem

Kaminari Gem: Complete Guide to Pagination in Ruby on Rails

When building web applications, managing large datasets efficiently is crucial to providing a smooth user experience. Pagination is one of the fundamental techniques that helps developers split large data into manageable chunks or pages. This not only improves performance but also enhances usability by avoiding overwhelming users with too much information at once.

For Ruby on Rails developers, Kaminari Gem is a powerful, flexible, and easy-to-use pagination solution. It has become one of the most popular gems to paginate ActiveRecord collections seamlessly. In this guide, you will learn everything you need to know about Kaminari โ€” from installation and setup to advanced customization and AJAX integration. Whether you’re a beginner or an experienced Rails developer, this comprehensive tutorial will help you implement and master pagination using Kaminari.

What is Kaminari?

Kaminari is a pagination gem for Ruby on Rails that provides a clean and customizable way to paginate data collections. It works smoothly with ActiveRecord queries and can also paginate plain Ruby arrays or any enumerable collection.

Key Features of Kaminari:

  • Simple and Clean API: Easy to set up and intuitive to use.
  • Customizable Pagination: Offers flexibility to customize the number of items per page, navigation links, and more.
  • ORM Agnostic: While designed for ActiveRecord, Kaminari supports other ORMs like Mongoid.
  • I18n Support: Built-in internationalization for pagination labels and UI.
  • Helpers and Views: Comes with view helpers that generate pagination controls compatible with CSS frameworks such as Bootstrap.
  • Friendly URLs and Caching: Supports SEO-friendly pagination URLs and works well with HTTP caching.

Supported Rails Versions

Kaminari supports Ruby on Rails versions 4 and above, including the latest Rails 7, ensuring compatibility with modern Rails applications.

Installing Kaminari

Adding Kaminari to your Rails project is straightforward.

Step-by-Step Installation

Add to Gemfile:

gem ‘kaminari’

Run Bundle Install:
Execute in your terminal:

bundle install

Verify Installation:
You can confirm the gem is installed by running:

rails console
Kaminari

If no errors appear, youโ€™re set.

Generate Kaminari Views (Optional):
To customize pagination views, run:

rails g kaminari:views bootstrap4

This command generates view partials compatible with Bootstrap 4.

Configuring Kaminari

Kaminari offers multiple configuration options to tailor pagination behavior.

Basic Configuration Options

Create an initializer file at config/initializers/kaminari_config.rb with the following defaults:

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

  • default_per_page: Number of records displayed per page by default.
  • max_per_page: Maximum number allowed to request per page.
  • window: Number of page links around the current page.
  • param_name: Query parameter name for page number (default :page).

Setting Per-Page Values Per Model

You can override pagination size on a per-model basis:

class User < ApplicationRecord
paginates_per 10
end

Or set a max per-page limit:

class User < ApplicationRecord
max_paginates_per 50
end

Internationalization (I18n)

Kaminari supports multiple languages. Add or modify locale files like:

en:
views:
pagination:
first: “First”
last: “Last”
next: “Next”
prev: “Prev”

This helps create localized pagination UI for global users.

Using Kaminari in Your Rails Application

Using Kaminari in Controllers

Pagination usually starts in the controller by modifying your ActiveRecord queries:

class ArticlesController < ApplicationController
def index
@articles = Article.order(created_at: :desc).page(params[:page]).per(10)
end
end

  • .page(params[:page]) tells Kaminari which page to fetch.
  • .per(10) overrides the default per-page count.

Using Kaminari in Views

Render pagination navigation links with the helper:

<%= paginate @articles %>

This renders a clean set of pagination links (e.g., Previous, 1, 2, 3, Next).

Customizing Pagination Views

You can customize the look by generating views:

rails g kaminari:views bootstrap4

Then edit the partials in app/views/kaminari/ to fit your design.

Using Kaminari with Bootstrap

Kaminariโ€™s Bootstrap-compatible views ensure pagination integrates seamlessly with Bootstrap styling:

<%= paginate @articles, theme: ‘bootstrap4’ %>

Customizing Pagination Helpers

You may want to customize pagination behavior or UI further.

  • Override default helpers in app/helpers/application_helper.rb.
  • Use Kaminariโ€™s API to change navigation labels.
  • Implement your own pagination components if needed.

Paginating Arrays and Non-ActiveRecord Collections

Kaminari can paginate any Ruby enumerable:

array = (1..100).to_a
@paginated_array = Kaminari.paginate_array(array).page(params[:page]).per(10)

This flexibility helps when paginating API responses or custom datasets.

Advanced Usage and Integration

AJAX Pagination with Kaminari

For seamless UX, Kaminari can be combined with AJAX to paginate without full page reloads.

Basic AJAX Setup:

  1. Modify your index action to respond to JS:

def index
@articles = Article.page(params[:page]).per(10)
respond_to do |format|
format.html
format.js
end
end

Create index.js.erb with:

$(“#articles”).html(“<%= j render ‘articles_list’ %>”);
$(“#pagination”).html(“<%= j paginate @articles %>”);

Adjust your view links for AJAX:

<%= render @articles %>
<%= paginate @articles, remote: true %>

This setup loads pages asynchronously, improving speed and usability.

Kaminari with Sinatra and Padrino

Kaminari supports other Ruby frameworks such as Sinatra and Padrino. While Rails has built-in helpers, Sinatra integration requires more manual setup but works similarly by paginating collections and rendering navigation links.

Demo: Creating a New Rails App with Kaminari

To see Kaminari in action, create a demo Rails app:

rails new kaminari_demo
cd kaminari_demo
bundle add kaminari
rails generate scaffold Article title:string body:text
rails db:migrate
rails db:seed # Add seed data for demo

Modify ArticlesController to paginate:

def index
@articles = Article.page(params[:page]).per(5)
end

In index.html.erb, add:

<%= paginate @articles %>

Start the server and browse to /articles to see paginated results.

Common Issues

  • No pagination links showing?
    Ensure you call paginate helper in the view and page in the controller.
  • Pagination params ignored?
    Confirm params[:page] is passed and not overridden elsewhere.
  • Styling issues?
    Use Kaminariโ€™s generated views compatible with your CSS framework.

Kaminari vs will_paginate

Feature

Kaminari

will_paginate

API

Chainable and scopes-friendly

Simpler but less flexible

Customization

Extensive with views and helpers

Less customizable

Framework Support

Rails, Sinatra, Padrino

Rails mainly

Internationalization

Built-in

Limited

Community & Updates

Active and maintained

Stable but slower updates

Kaminari is a robust, flexible pagination solution that integrates seamlessly with Ruby on Rails applications. Its clean API, customization options, and support for modern Rails versions make it a top choice for developers aiming to handle large datasets gracefully.

Whether you are building a simple blog or a complex e-commerce site, Kaminari helps deliver data in digestible chunks, enhancing both performance and user experience.

Get started with Kaminari today and elevate your Rails applications with smooth, efficient pagination!

Frequently Asked Questions (FAQs)

Kaminari is a Ruby gem designed to paginate large collections of data in Rails apps efficiently.

Add gem 'kaminari' to your Gemfile, run bundle install, and configure as needed.

Yes, Kaminari supports paginating plain Ruby arrays with paginate_array.

Yes, Kaminari can be integrated with AJAX for dynamic page loading without reloads.

Yes, Kaminari supports Rails 7 and continues to be maintained actively.

Similar Posts