Learn Clould Application Development and DevOps

The Blackninja Blog

Expand your Cloud Application Development and DevOps knowledge with detailed tutorials and case studies.

Pagination in Ruby on Rails with the Pagy Gem

I’ve just recently begun working with Rails again, after a few years of working exclusively with Node. I’m in the process of developing an app that naturally requires some pagination. I’ve had experience with will_paginate years back, but after doing some research, I decided to give pagy a try. You can read a really good breakdown, that compares Pagy to will_paginate and Kaminari at the Imaginary Blog.

Personally, I found the documentation a little unclear. To get yourself up and running with Pagy, here’s what you need to do.

To set the stage, let’s assume your application has:


/controllers/UsersController
/helpers/users_helper.rb
/users/index.html.erb

Currently, your index method is returning all users and your view is simply outputting them. Assuming you have 100 users in your database, that’s going to be a lot of users to render on a single screen. Let’s set this up so that we only render 9 users per page.

Add pagy to your Rails Application

Add the pagy gem to your Gemfile


gem 'pagy'

Don’t forget to bundle install and restart your rails server

Update your controller to include the pagy gem


class UsersController < ApplicationController
  include Pagy::Backend

  def index
    @pagy, @users = pagy(User.all, page: params[:page], items: 9)
  end
end

If you don’t specify the items per page, the default is 20. You can also set it in the pagy.rb initializer file, which I’ll discuss below.

Update your helper to include the pagy gem


module UsersHelper
  include Pagy::Frontend
end

Add pagy_nav to your view


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

That should get you going. When you render the index view, you should see 9 items per page, with the paging controls visible to allow you to switch between pages.

pagy-nav

Styling pagy with Bulma

I’m using Bulma.io as a CSS framework for my app. I wanted to incorporate the styles they have for paging controls. Thankfully, Pagy has some documentation around this.

The first thing you need to do is create a pagy.rb initializer file in your initializers folder. You can also download a sample initializer file from Pagy directly. If you choose to download the file, place it in your initializers folder and uncomment the logic for bulma. If you’re creating the file from scratch, just add the following line:


  require 'pagy/extras/bulma'

Don’t forget to restart your rails server

Update your index.html.erb reference the bulma version of the paging controls.


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

Your final version should look like this:

pagy-bulma-nav