Setting up Pagination With Will_Paginate Gem
One of the few gems out there that make it easy for pagination is will_paginate. With the gem will_paginate, it's super easy to do, too. While there are a few other options for pagination (which will be covered soon), this is one of the easiest to get up and running.
First thing to do is add the gem to your gem file and install it.
gem 'will_paginate', '~> 3.3', '>= 3.3.1'
Then in terminal:
bundle install
What I love about the latest update to gem, it now has Active Record support allowing you to daisy chain it in your controller, like this. As you can see in the example below, I have attached the paginate command after my published scope.
@posts = Post.all.order("pub_date DESC").published.page(params[:page])
The next thing you will need to do is to define in your model how many items per page. In my example above, it would be adding this to the post.rb in the models folder.
self.per_page = <pick number>
So, my completed post model looks like this now.
class Post < ApplicationRecord
has_rich_text :content
has_many :comments, dependent: :destroy
acts_as_taggable_on :tags
scope :published, -> { where("pub_date <=?", Time.now) }
self.per_page = 8
end
In your view where your posts shows up, such as the index.htm.erb file, you will need to add the pagination links where you want them. That's as simple as adding this line:
<%= will_paginate @posts %>
Note: Be sure to restart your server or you will get an error if you were adding this code while running the server.
The final piece is to stylize the pagination links with css of your liking. Happy paginating.