Why Pagination ?
As our list of record accumulates, we would not want to show the entire list of records in a single page, as this is impractical and will cause our rails app to get slower and slower and as well as degrade the performance of our database server. So, an easy way to fix that issue is to add pagination to our rails apps. This will limit the number of records that we want to show in a single page. We can also specify the number of records that we want to add per page, and as well as customize the look of pagination.
There are a lot of gems that you can use to add pagination to your app, gems like kaminari, will_paginate, pagy, etc. Here i’ll show you how to do it with kaminari. If you have a rails application with huge number of records for example a million records or more, consider using pagy instead of kaminari or will_paginate, as it is gives better performance. But for small applications kaminari is fine.
- Kaminari Github Link: https://github.com/kaminari/kaminari
- Will Paginate Github Link: https://github.com/mislav/will_paginate
- Pagy Github Link: https://github.com/ddnexus/pagy
Adding Pagination With Kaminari
To add pagination with Kaminari, first add kaminari to your gemfile and run bundler
#File: Gemfile gem 'kaminari'
In your controller add the kaminari scope, in the method that you want pagination, for instance i added it in my index method. You can limit the number of records that you want per page, for instance if i want 10 records to show per page then i would add .page(params[:page]).per(10)
#File: app/controllers/book_controller.rb class BooksController < ApplicationController def index @books = Book.order("created_at DESC").page(params[:page]).per(10) end end
Kaminari also comes with it’s own views, to generate those views simply run the following command, this will generate kaminari views with the default theme
rails g kaminari:views default
You can also generate kaminari views with other themes, for eg bootstrap4. Checkout kaminari themes here: https://github.com/amatsuda/kaminari_themes
rails g kaminari:views bootstrap4
You can also customize the views generated by kaminari in app/views/kaminari/
After that, add kaminari to your views, for example this is index view of my book records
#File: app/views/books/index.html.erb <div class="pagination"> <%= paginate @books %> </div>
More on Pagination
Kaminari supports other template engines as well (haml, slim, etc). You can also generate a kaminari config, to configure kaminari as per your specific requirements or configure it all from one place, checkout kaminari docs for more info: https://www.rubydoc.info/gems/kaminari/0.17.0