Pagination with Kaminari in Rails made simple.

paginate

For a Rails web application, I needed to implement pagination. I made some research from people who have done pagination on rails projects to know the best to settle down for. After some conversations, Kaminari was the only gem mentioned by several people. If you’re somewhat a lazy programmer who likes to get things done asap in the most effective, efficient and easiest way – Round of applause for being here.

Also on the Railscast video on implementing pagination with Kaminari, I heard the same comment by Ryan Bates:

“I think it’s a much cleaner implementation than will-paginate”

So I checked the Kaminari gem, and found out it’s pretty easy to implement. At this point, I assume you have an existing model to implement the pagination. The name of my model is Post. Let’s get started.

First and First:

Include the gem in your gemfile and then run bundle in your terminal

gem 'kaminari'

Implementing in a Rails Engine:

N.B=> I’m using the kaminari gem in a rails engine which is part of a big rails application. If you’re implementing it in a rails engine like I am, include it as a dependency in your engine gemspec like this.

s.add_dependency 'kaminari'

Implementing in the controller:

Next thing is to proceed to the action in your controller, in my case is posts_controller.rb

class PostsController < ApplicationController
   def index
      @venues = Post.page(params[:page])
   end
end

By default, kaminari loads 25 records by page but if you want 10 records by page like me, you can edit the above code like this:

def index
   @posts=Post.page(params[:page]).per(10)
end

Implementing in the view:

Then proceed above to the view you want to implement your pagination and add this:

<%= paginate @posts %>

Voila, and you are done with the pagination. Indeed, I agree that kaminari is pretty simple easy to follow.

The default view template for the Kaminari paginator will wrap the page links in span-elements. I used bootstrap framework to make the design more appealing. It’s all left to you to re-design the element to your taste. If you don’t want to invest your time in customizing the view templates, there also a possibility to fetch : https://github.com/amatsuda/kaminari_themes

Kindly feel free to post your questions/comments below.

You may also like