[Awesome Ruby Gem] Use kaminari gem to paginate records

kaminari

kaminari is a Scope & Engine based, clean, powerful, customizable and sophisticated paginator for modern web app frameworks and ORMs.

Features

  • Clean

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

  • Easy to Use

    Just bundle the gem, then your models are ready to be paginated. No configuration required. Don’t have to define anything in your models or helpers.

  • Simple Scope-based API

    Everything is method chainable with less “Hasheritis”. You know, that’s the modern Rails way. No special collection class or anything for the paginated values, instead using a general AR::Relation instance. So, of course you can chain any other conditions before or after the paginator scope.

  • Customizable Engine-based I18n-aware Helpers

    As the whole pagination helper is basically just a collection of links and non-links, Kaminari renders each of them through its own partial template inside the Engine. So, you can easily modify their behaviour, style or whatever by overriding partial templates.

  • ORM & Template Engine Agnostic

    Kaminari supports multiple ORMs (ActiveRecord, DataMapper, Mongoid, MongoMapper) multiple web frameworks (Rails, Sinatra, Grape), and multiple template engines (ERB, Haml, Slim).

  • Modern

    The pagination helper outputs the HTML5

Installation

You can install it as a gem:

1
$ gem install kaminari

or add it into a Gemfile (Bundler):

1
2
3
4
5
# Gemfile

# kaminari/kaminari: ⚡ A Scope & Engine based, clean, powerful, customizable and sophisticated paginator for Ruby webapps
# https://github.com/kaminari/kaminari
gem 'kaminari', `4.1.0'

Then, run bundle install.

1
$ bundle install

Query Basics

The page Scope

To fetch the 7th page of users (default per_page is 25)

1
User.page(7)

Note: pagination starts at page 1, not at page 0 (page(0) will return the same results as page(1)).


You can get page numbers or page conditions by using below methods.

1
2
3
4
5
6
7
8
9
User.count                     #=> 1000
User.page(1).limit_value #=> 20
User.page(1).total_pages #=> 50
User.page(1).current_page #=> 1
User.page(1).next_page #=> 2
User.page(2).prev_page #=> 1
User.page(1).first_page? #=> true
User.page(50).last_page? #=> true
User.page(100).out_of_range? #=> true

The per Scope

To show a lot more users per each page (change the per_page value)

1
User.page(7).per(50)

Note that the per scope is not directly defined on the models but is just a method defined on the page scope. This is absolutely reasonable because you will never actually use per_page without specifying the page number.


Keep in mind that per internally utilizes limit and so it will override any limit that was set previously. And if you want to get the size for all request records you can use total_count method:

1
2
3
4
User.count                     #=> 1000
a = User.limit(5); a.count #=> 5
a.page(1).per(20).size #=> 20
a.page(1).per(20).total_count #=> 1000

The padding Scope

Occasionally you need to pad a number of records that is not a multiple of the page size.

1
User.page(7).per(50).padding(3)

Note that the padding scope also is not directly defined on the models.


Unscoping

If for some reason you need to unscope page and per methods you can call except(:limit, :offset)

1
2
users = User.page(7).per(50)
unpaged_users = users.except(:limit, :offset) # unpaged_users will not use the kaminari scopes

Configuring Kaminari

General Configuration Options

You can configure the following default values by overriding these values using Kaminari.configure method.

1
2
3
4
5
6
7
8
9
10
default_per_page      # 25 by default
max_per_page # nil by default
max_pages # nil by default
window # 4 by default
outer_window # 0 by default
left # 0 by default
right # 0 by default
page_method_name # :page by default
param_name # :page by default
params_on_first_page # false by default

There’s a handy generator that generates the default configuration file into config/initializers directory. Run the following generator command, then edit the generated file.

1
% rails g kaminari:config

Changing page_method_name

You can change the method name page to bonzo or plant or whatever you like, in order to play nice with existing page method or association or scope or any other plugin that defines page method on your models.

Configuring Default per_page Value for Each Model by paginates_per
You can specify default per_page value per each model using the following declarative DSL.

1
2
3
class User < ActiveRecord::Base
paginates_per 50
end

Configuring Max per_page Value for Each Model by max_paginates_per
You can specify max per_page value per each model using the following declarative DSL. If the variable that specified via per scope is more than this variable, max_paginates_per is used instead of it. Default value is nil, which means you are not imposing any max per_page value.

1
2
3
class User < ActiveRecord::Base
max_paginates_per 100
end

Configuring params_on_first_page when using ransack_memory

If you are using the ransack_memory gem and experience problems navigating back to the previous or first page, set the params_on_first_page setting to true.

Paginating Without Issuing SELECT COUNT Query

Generally the paginator needs to know the total number of records to display the links, but sometimes we don’t need the total number of records and just need the “previous page” and “next page” links. For such use case, Kaminari provides without_count mode that creates a paginatable collection without counting the number of all records. This may be helpful when you’re dealing with a very large dataset because counting on a big table tends to become slow on RDBMS.

Just add .without_count to your paginated object:

1
User.page(3).without_count

Paginating a Generic Array object

Kaminari provides an Array wrapper class that adapts a generic Array object to the paginate view helper. However, the paginate helper doesn’t automatically handle your Array object (this is intentional and by design). Kaminari::paginate_array method converts your Array object into a paginatable Array that accepts page method.

1
@paginatable_array = Kaminari.paginate_array(my_array_object).page(params[:page]).per(10)

You can specify the total_count value through options Hash. This would be helpful when handling an Array-ish object that has a different count value from actual count such as RSolr search result or when you need to generate a custom pagination. For example:

1
@paginatable_array = Kaminari.paginate_array([], total_count: 145).page(params[:page]).per(10)

or, in the case of using an external API to source the page of data:

1
2
3
page_size = 10
one_page = get_page_of_data params[:page], page_size
@paginatable_array = Kaminari.paginate_array(one_page.data, total_count: one_page.total_count).page(params[:page]).per(page_size)

For More Information

Check out Kaminari recipes on the GitHub Wiki for more advanced tips and techniques. Kaminari recipes · kaminari/kaminari Wiki - https://github.com/kaminari/kaminari/wiki/Kaminari-recipes

See Views - https://github.com/kaminari/kaminari#views, Helpers - https://github.com/kaminari/kaminari#helpers to learn more.

References

[1] kaminari/kaminari: ⚡ A Scope & Engine based, clean, powerful, customizable and sophisticated paginator for Ruby webapps - https://github.com/kaminari/kaminari

[2] kaminari | RubyGems.org | your community gem host - https://rubygems.org/gems/kaminari/