Setting Up Pagination in Your Rails 6 App with Will_Paginate Gem

I decided to add some pagination when creating this site because after about 8 articles on the page, it just looks silly. With the gem will_paginate, it's super easy to do, too. 

First thing to do is add the gem to your gem file and install it.

gem 'will_paginate', '~> 3.3'

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.


0 Comments


Please log in to leave a reply.