After a few days of much-needed break, it was time to get back to adding features to my blog project. Today's assignment was adding pagination to the blog posts. In order to get this feature working, I used the will_paginate gem. On the gem file, I added
gem 'will_paginate', '~> 3.1', '>= 3.1.6', and ran a quick
bundle install that install the required gem.
Then, it was all about following the documentation of the gem.
First, off I updated the posts controller for my index method.
def index @post = Post.all.order('created_at DESC').paginate(:page => params[:page], :per_page => 3) end
As you can see the
.paginate has been added, and I've followed the documentation. Also, I had set three articles to be shown per page.
Once this was done, the page updated itself to show only three articles on a page. Now I needed to add the pagination in the view itself so that the users can navigate on the website. For this, I used
<%= will_paginate @post %>
Once this was done, I got the pagination working with a navigation menu. However, I still needed to add a bit of style to the menu so that they looked good. For this, I could use bootstrap, something that I had already been using for my app.
I used the gem bootstrap_will_paginate for this via
gem 'bootstrap-will_paginate', '~> 1.0'. Again, I ran bundle install, and finally on the views, I added the styling by following the documentation of the gem.
<%= will_paginate(@post, :renderer => WillPaginate::ActionView::Bootstrap4LinkRenderer) %>
The pagination was now ready to be used.