Rails 6 Database Record Pagination with Kaminari
22nd December 2020
Kaminari is a Gem that can be used with Rails to make paginating records super simple.
In this post I will show you how to add pagination to your rails app using the Kaminari gem and style the paginator with Bootstrap and Font Awesome.
The following software was used in this post.
- Rails - 18.104.22.168
- Kaminari - 1.2.1
- Bootstrap - 5.0.0-beta1
- Font Awesome (Free) - 5.15.1
Add the Kaminari gem to your Gemfile
# Gemfile gem 'kaminari', '~> 1.2.1'
Then use bundle to install the gem.
Set the controller views methods that require pagination to paginate records with the below query.
# app/controllers/users_controller.rb def index @users = User.order(:name).page params[:page] end
In the view that require pagination use the paginate helper to magically paginate the records.
<%# app/views/users/index.html.erb %> <%= paginate @users %>
Thats it! Your records are paginated and you have links on your view for the pages of records. The default styling however it super simple and not very 2020 bling bling.
There are a number of themes that can be used to change to look of the paginator.
To use the bootstrap paginator, there is a handy kaminari generator. The generator creates template files that will be used to render the bootstrap paginator.
Even though I am using bootstrap 5 the bootstrap4 theme still works without issues.
rails generate kaminari:views bootstrap4
The templates can be found in the app/views/kaminari folder.
The default << First < Previous Next > Last >> tags are a bit lame. Luckily you can use Font Awesome icons in their place.
In the config/locals/en.yml file add the following views config under the en section.
en: views: pagination: next: '<i class="fas fa-angle-right"></i>' previous: '<i class="fas fa-angle-left"></i>' first: '<i class="fas fa-angle-double-left"></i>' last: '<i class="fas fa-angle-double-right"></i>'
This will change the text to use these nice chevron style arrows instead.
Customize these according to the tastes of your app.
In this post we added pagination to our Rails 6 app utilising the Kaminari Gem and styled the paginator with Bootstrap and Font Awesome.