[Ruby on Rails] Introduced paging function


Create a paging function, Prevents slowdown in image loading speed when displaying a list

Development environment

ruby 2.5.7 Rails OS: macOS Catalina


This time, we will introduce gem'kaminari' and implement the paging function.

Flow until the introduction of kaminari


gem 'kaminari','~> 1.2.1'


$ bundle install
$ rails g kaminari:config
$ rails g kaminari:views default

This completes the installation.

How to use

I will introduce the ones that I often use personally. https://github.com/kaminari/kaminari Detailed usage is described here, so If you are interested, please see here. However, it is all in English.

Basic paging

Install the following where you want to paging. Links to pages 1 and 2 and to the next will also appear at this location.


<%= paginate @posts %>

Paging can be implemented by writing the controller like this.


@posts = posts.page(params[:page])
Supplement [page (params [: page])] It's okay to think that page (params [: page]) ≒ all.

Sorting paging

It is possible to reverse the order by adding a note to the description of the controller.


@posts = posts.page(params[:page]).reverse_order

Specify the number of items to be displayed per page


  Kaminari.configure do |config|
    config.default_per_page = 5 #Specify the maximum number of items that can be displayed per page on all pages that use kaminari with this number.

Display individually When specifying the number of items to be displayed per page


@posts = posts.page(params[:page]).per(10)
Supplement [Display priority] As the priority is given to the number in kaminari_config.rb, kaminari_config.rb >= homes_controller.rb Please give the superiority or inferiority of such numbers.

Change the display

If you want to change next, last, etc.

Introduced 1 gem'rails-i18n' 2 Create a config / locals / ja.yml file 3 Edit ja.yml

If you do the above, it's OK. [Reference of ja.yaml]


      first: "≪"
      previous: "<"
      next: ">"
      last: "≫"

When applying to an array

When implementing by the above method, if the value is an array, it will not be displayed, so It should be described as follows.


@posts = Kaminari.paginate_array(Array).page(params[:page])

Actual description: [Ruby on Rails] Ranking display (total, average value)

Other functions

[Rails] Automatically go to the next page! !! Infinite scrolling of pagination with jscroll

There are many others, so if you are interested, please check it out.


The introduction itself is not that difficult, but without the paging function As the site grows, it loads slowly and is unusable, so Some kind of paging function is essential.

Also, on twitter, technologies and ideas that are not uploaded to Qiita are also uploaded, so I would be grateful if you could follow me. Click here for details https://twitter.com/japwork

Recommended Posts