Pagy Gem

Andrew Smoker
2 min readJun 29, 2021

Recently, I came across the gem “Pagy” that helps to handle pagination in Rails applications and thought it would be good to review how to include it. Pagination is so important as your database grows because no one wants to scroll through hundreds or thousands of posts. However, someone might click through a few pages if there are only 10 posts per page. “Pagy” has some benchmarks listed in their docs that show it performing better than other standard pagination gems, so I decided to go with it.

The first step is to add the gem to the gemfile and run bundle install.

gem 'pagy'

Pagy splits pagination into the frontend and backend so in order to set our data up correctly on the backend and show it correctly on the front end we need to do a little configuration. For this application, I have a Post and User model and I want the index of Posts to show only 10 per page. If I know that posts are the only model I want paginated, I write some code in the Post Controller, but if I might use it for multiple models, I write it in the Application Controller as below:

class ApplicationController < ActionController::Base
include Pagy::Backend
end

This gives us access to Pagy on the backend. For the frontend, I need to include it in our Application Helper as below. Again, if I only wanted it for posts, I could write this directly in the Post Helper.

module ApplicationHelper
include Pagy::Frontend
end

Now we have access to Pagy but need to tell the controller and view to actually use it. In the post controller for the index of posts instead of writing @post = Post.all, write this line:

def index
@pagy, @posts = pagy(Post.all, items: 10)
end

This assigns posts to a @pagy variable in addition to the @posts variable. The items parameter specifies how many objects (in this case posts) to display on each page and can be modified very easily. Now we tell our view how to handle the @pagy variable. So in the index view for posts we write:

<%== pagy_nav(@pagy).html_safe%>

This displays the pagination in the default format of Prev, page numbers and Next. There are many customizations available for Pagy including Bootstrap so definitely take advantage of how to customize the view. If I start my server and access “/posts” I now see 10 posts per page with pagination at the bottom and I can easily navigate between pages. It’s that simple! I hope this was helpful and encourage everyone to continue researching new gems to make applications even better!

--

--

Andrew Smoker

I am 34 years old and making a huge career change by attending Flatiron School’s Software Engineering Bootcamp. Excited to learn!