Using Pagy Gem for Pagination in Rails 7 App
On a previous article, I showcased the Will_Paginate Gem. But since then, several other pagination gems have come about like Kaminari and now Pagy. But what makes Pagy especially a compelling choice to use is its superior performance and lower overall footprint. For a breakdown on just how much better Pagy is, check out this article from Tiago Franco on Imaginary Cloud.
Once you decide to use Pagy, let's get started.
First, install the gem in your project by adding the following to your Gemfile.
gem 'pagy', '~> 5.10', '>= 5.10.1'
Now, be sure to run the "bundle install" command in your terminal.
Next head over to your application_controller.rb the in app/controllers folder.
Inside there you'll need to add the reference to Pagy like so:
class ApplicationController < ActionController::Base
include Pagy::Backend
Technically, you could just include the above line on a specific controller (such as articles or posts), but in my case, I wanted the ability to access Pagy from all controllers and opted for the application controller since all controllers inherit from the application controller.
In my specific example, I will be paginating articles on this site. The next step is to head over to the articles_controller.rb and make some adjustments.
Originally, my index of all articles looked like this:
@articles = Article.order("pubdate DESC")
But now, it needs to be changed to this:
@pagy, @articles = pagy(Article.order("pubdate DESC"), items: 8)
Notice you can pass in the "items" variable which will determine how many items per page to paginate.
Now we need to make sure that Pagy is accessible in the Views. To do that go into the application_helper.rb in the helpers folder and add the line below:
module ApplicationHelper
include Pagy::Frontend
Next, we need to get the pagination on the index page. Again since I am working with articles, we need to go to the index.html.erb file in the articles folder.
Below the loop for the articles, we will need to add the Pagy navigation, like below. Note, the double "==" which converts the html to raw. If not, you will get text output of the HTML.
<% @articles.each do |article| %>
...
<% end %>
<%== pagy_nav(@pagy) %>
The last thing to do would be to style the pagination. There are several pre-built extra you can include in your application helper for popular frameworks like Bootstrap and Bulma. There's also good documentation to style if you are using Tailwind. Get all the documentation for extra here.