skip to content

Pagy Series & Helpers

Pagy 43 replaced its helper modules with one pagy method returning a Pagy object and the page's records, plus helpers called on that object. Interviewers check the current API and paginator choice.

part ofRuby on Railsread it →
on this pageshow

explore

questions

5

With Pagy 43 in Rails 8.1, how do you paginate an admin product list in the controller and render its page links?

level: juniorimportance: must knowfreq 50%

answer

  1. one module in ApplicationController
  2. pagy returns two values
  3. default paginator :offset, limit 20
  4. helpers are methods on @pagy
  5. <%== for the nav string

basics

~10 s

Include Pagy::Method in ApplicationController, assign @pagy, @products = pagy(:offset, Product.order(:name)) in the action, and print <%== @pagy.series_nav %> in the view; Pagy 43 helpers are methods on @pagy that return HTML strings.

solid answer

~40 s

In Pagy 43 you `include Pagy::Method` once, usually in `ApplicationController`, and the action calls `@pagy, @products = pagy(:offset, Product.order(:name))`. The method reads the `page` param from the request, runs a `COUNT` and an `OFFSET`/`LIMIT` query, and returns a `Pagy::Offset` object plus the page's records as a lazy relation. The view iterates `@products` and calls helpers on the object: `<%== @pagy.series_nav %>` for the link bar and `<%== @pagy.info_tag %>` for a line like "Displaying items 41-60 of 324 in total". Those helpers return plain strings rather than `html_safe` ones, hence `<%==`. The default `limit` is 20; pass `limit:` per call or set `Pagy::OPTIONS[:limit]` in the initializer. The pre-43 `include Pagy::Backend` and `pagy_nav(@pagy)` no longer exist.

code

ruby · 7 lines
ruby
class Admin::ProductsController < ApplicationController
  include Pagy::Method # or once in ApplicationController

  def index
    @pagy, @products = pagy(:offset, Product.order(:name))
  end
end

go deeper

for a junior

Recall the three moves: include Pagy::Method, destructure @pagy and the records from pagy(:offset, scope), and print @pagy.series_nav with <%==. Know the default of 20 rows.

for a middle

Explain what the call runs (a COUNT plus an OFFSET/LIMIT select), why the records stay a lazy relation, and how limit:, client_limit: and Pagy::OPTIONS interact.

for a senior

Spot pre-43 code in a codebase, explain the empty-page default for out-of-range requests, and know when the COUNT on :offset is worth replacing with another paginator.

for a principal

Frame the gem choice for a team: Pagy's explicit paginator argument against scope-style pagination, and a convention for where page size and client limits are set.

## What Pagy 43 changed **Pagy** is a pagination gem for Rack apps, Rails included. Version 43 (it jumped from 9.3.4 straight to 43.0.0) is a **complete redesign**, not a routine major: the old `Pagy::Backend` and `Pagy::Frontend` modules, the `pagy_nav(@pagy)` style helpers and every `require 'pagy/extras/...'` file are gone. What replaced them is smaller: - one module, `Pagy::Method`, that defines a single `pagy` method; - a first argument naming the **paginator** (`:offset`, `:countish`, `:countless`, `:keyset` and a few more); - **helpers that are instance methods** of the object `pagy` returns, such as `@pagy.series_nav` and `@pagy.info_tag`; - one global options hash, `Pagy::OPTIONS`, set in `config/initializers/pagy.rb`. Pagy has no Rails dependency of its own, and version 43 needs Ruby 3.3 or newer, which a Rails 8.1 app on Ruby 3.4 or 4.0 already meets. ## The controller side `Pagy::Method` defines `pagy` as a **protected** method that reads `self.request`, so it belongs in a controller. Including it in `ApplicationController` makes it available to every action: ```ruby class ApplicationController < ActionController::Base include Pagy::Method end class Admin::ProductsController < ApplicationController def index @pagy, @products = pagy(:offset, Product.order(:name), limit: 25) end end ``` The call returns a **two-element array**, destructured into `@pagy` (the pagination object) and `@products` (this page's records). With `:offset`, the default paginator when the symbol is omitted, Pagy: 1. reads `page` from the query string (a missing, zero, negative or non-numeric value becomes page 1); 2. runs `collection.count(:all)`, a `SELECT COUNT(*)`; 3. returns `collection.offset(offset).limit(limit)`, still a lazy `ActiveRecord::Relation`, so the select runs when the view iterates it. ## What the object knows | reader | meaning on page 3 of 324 items, limit 20 | |---|---| | `page` | 3 | | `limit` | 20 | | `count` | 324 | | `last` (alias `pages`) | 17 | | `from` / `to` | 41 / 60 | | `previous` / `next` | 2 / 4 (nil at the edges) | ## The view side ```erb <% @products.each do |product| %> <%= render product %> <% end %> <%== @pagy.info_tag %> <%== @pagy.series_nav %> ``` `series_nav` returns a `<nav class="pagy series-nav">` holding previous and next arrows, page links with `rel="prev"`/`rel="next"`, the current page marked `aria-current="page"`, and a `:gap` ellipsis. It shows **7 slots** by default; `slots: 9` widens it and `compact: true` drops the first/last anchoring. `series_nav(:bootstrap)` and `series_nav(:bulma)` emit those frameworks' markup. Pagy builds the markup itself and returns a **plain `String`**, so ERB's `<%=` would escape it into visible text; `<%==` prints it as is (the escaping rules themselves belong to Action View). ## Options and defaults - `limit:` sets the page size; Pagy's own default is **20**. - `Pagy::OPTIONS[:limit] = 25` in the initializer changes it globally; the generated initializer then calls `Pagy::OPTIONS.freeze`. - `client_limit: 100` lets a `?limit=` param choose a size up to 100; without it the param is ignored. - `page_key:` and `limit_key:` rename the query params (strings, defaults `'page'` and `'limit'`). - A page past the end, such as `?page=999`, gives an **empty page** whose `previous` points at the last page; `raise_range_error: true` raises `Pagy::RangeError` instead. ## Two lists, Turbo Frames and other wiring An admin dashboard often shows two paginated lists at once, say products and recent orders. Both would read the same `page` param, so give one its own key: ```ruby @pagy, @products = pagy(:offset, Product.order(:name)) @orders_pagy, @orders = pagy(:offset, Order.order(id: :desc), page_key: "orders_page") ``` Each object builds its links from the current request params and changes only its own key, so paging the orders keeps the products on their page. `root_key: "orders"` nests both keys instead (`orders[page]=2`). When the list sits inside a Turbo Frame, `anchor_string: 'data-turbo-frame="products"'` adds that attribute verbatim to every anchor Pagy renders, so a click replaces only the frame. Pagy trusts that string as raw HTML, so never build it from user input. ## Common mistakes - Copying a pre-43 tutorial: `include Pagy::Backend` raises `NameError`, and `pagy_nav` no longer exists. - Passing `items:`. That option became `limit:` back in Pagy 9.0, and Pagy 43 simply ignores the unknown key. - Expecting 25 rows: that is Kaminari's default, not Pagy's. - Forgetting an `order`. `OFFSET` over an unordered relation can return rows in any order the database likes, so pages can overlap.

  • With Pagy 43, what happens when someone requests ?page=999 on a 50-page product list?
    Pagy serves an empty page rather than raising: the records are empty, `from`, `to` and `in` are 0, and `previous` points at page 50, so the nav still offers a way back. To make it raise, pass `raise_range_error: true` (per call or in `Pagy::OPTIONS`); Pagy then raises `Pagy::RangeError`, a subclass of `Pagy::OptionError`.
  • How would you let an admin pick 50 rows per page through the URL?
    Allow it explicitly with `client_limit:`, for example `pagy(:offset, scope, client_limit: 100)`. Pagy then reads `?limit=50` and honours it, silently capping anything above 100. Without `client_limit` the `limit` param is ignored and the configured `limit` (20 by default) applies. `limit_key:` renames the param.

  • Writes include Pagy::Backend and pagy_nav(@pagy), the API Pagy 43 removed.
  • Prints the nav with <%= @pagy.series_nav %> and expects clickable links.
  • Sets the page size with items: 30, an option renamed to limit in Pagy 9.
  • Expects 25 rows per page by default, which is Kaminari's default_per_page.
  • Says pagy returns a relation with page methods instead of a [pagy, records] pair.

Assumes Pagy 43.7 on Rails 8.1; Pagy 43 replaced Pagy::Backend, Pagy::Frontend and pagy_nav(@pagy) with include Pagy::Method and helpers on @pagy.

open as a page

In a Rails API controller using Pagy 43, how do headers_hash, data_hash and client_limit expose pagination metadata and let a client choose its page size?

level: middleimportance: should knowfreq 28%

basics

~10 s

@pagy.headers_hash returns a link header plus current-page, page-limit, total-count and total-pages to merge into response.headers; @pagy.data_hash returns selected numbers and URLs for a JSON body; client_limit: caps a ?limit= request.

open as a page

With Pagy 43, what SQL does pagy(:offset, scope) run per page, and what do the :countish and :countless paginators change about it?

level: middleimportance: should knowfreq 38%

basics

~20 s

:offset runs a COUNT plus an OFFSET/LIMIT select on every page. :countish counts once, or again after an optional ttl:, and carries the total in its page links. :countless never counts: it fetches limit + 1 rows to learn whether a next page exists.

open as a page

With Pagy 43, when you move a million-row admin audit log to pagy(:keyset, ...), what must the relation and database provide, and what does the UI lose?

level: seniorimportance: should knowfreq 30%

basics

~20 s

pagy(:keyset) needs a uniquely ordered relation, usually ending in :id, and an index matching those columns and directions. It returns no count, previous or last page, so navigation is forward-only: next_tag and page_url(:next), not series_nav.

open as a page

When upgrading a Rails app from Pagy 9 to Pagy 43, which controller, view and initializer code must change, and how does out-of-range page handling differ?

level: seniorimportance: should knowfreq 24%

basics

~10 s

Replace include Pagy::Backend with Pagy::Method, drop Pagy::Frontend, turn pagy_nav(@pagy)-style helpers into @pagy methods, move Pagy::DEFAULT settings to Pagy::OPTIONS and delete the extras. Out-of-range pages now render empty by default instead of raising.

open as a page