With hundreds and thousands of posts on website, we would like to insert some breaks. The first choice for pagination in Rails is will_paginate. However, I find a better one called Kaminari.
Controllers and Views
First, add ‘kaminari’ to ‘Gemfile’ and run
Second, we apply the scope called
per in our Controller.
@posts = Post.all.page(params[:page]).per(15)
that will show 15 posts per each page.
Then, we call
paginate helper in our views.
<%= paginate @posts %>
Configure the default value
rails g kaminari:config and change the file
kaminari_config.rb in config/initializers
I18N and labels
We can change the default labels in config/locales.
Configure the default view
rails g kaminari:views default and change the files in app/views/kaminari
e.g. I delete the first and last label in _pagination.html.erb and change the style to bootstrap according to the theme provided by the Kaminari.
I followed the instruction on Railscasts and the wiki of Kaminari. But my case seemed more complicated. I set three posts per page as default for test, but found that the posts presented in a strange array.
The problem was that 3 posts each time was passed into the partial and was implemented the reverse scope. So I deleted the
reverse scope and changed the line in the controller like this: