skip to content

Kaminari Scopes & Themes

Kaminari adds page and per scopes to relations and a paginate helper with generated view themes. Interviewers probe its extra COUNT query, without_count, and capping client-chosen page sizes.

part ofRuby on Railsread it →
on this pageshow

explore

questions

5

In a Rails app using Kaminari, how do you paginate job listings with page and per, and render the page links in the view?

level: juniorimportance: must knowfreq 46%

answer

  1. a class method on every model
  2. page(params[:page]), then per
  3. 25 per page by default
  4. paginate @listings in the view
  5. page_entries_info for the summary

basics

~20 s

Call Listing.order(posted_at: :desc).page(params[:page]).per(20) in the controller and <%= paginate @listings %> in the view. Kaminari adds page to every Active Record model, per exists only on that page scope, and the default size is 25.

solid answer

~40 s

Kaminari adds a `page` class method to every Active Record model. `Listing.order(posted_at: :desc).page(params[:page])` returns a relation with `LIMIT 25` and the matching `OFFSET`; a missing, non-numeric or negative page becomes page 1. `per(20)` changes the size, but it is defined only on that page scope, so `Listing.per(20)` raises `NoMethodError`. In the view, `<%= paginate @listings %>` renders a `nav` of page links that keep the other query params, and it renders nothing when there is only one page. `<%= page_entries_info @listings %>` prints "Displaying listings 21 - 40 of 312 in total". Both helpers need the total, so rendering them usually runs a `COUNT` beside the page query. The relation also answers `current_page`, `total_pages`, `next_page`, `prev_page`, `first_page?` and `last_page?`.

code

ruby · 5 lines
ruby
class ListingsController < ApplicationController
  def index
    @listings = Listing.order(posted_at: :desc).page(params[:page]).per(20)
  end
end

go deeper

for a junior

Recall page(params[:page]).per(n) in the controller, paginate and page_entries_info in the view, and the default of 25 per page.

for a middle

Explain why per only exists after page, what LIMIT and OFFSET page builds, and that paginate usually needs a COUNT for its links.

for a senior

Handle the edges: out-of-range pages, padding for featured rows, a stable order, and the COUNT cost on big tables.

for a principal

Decide whether a long-lived app keeps a scope-based pagination gem last released in 2021, and what a replacement would have to match.

## What Kaminari adds **Kaminari** is a scope-based pagination gem. Its `page` method is defined on every Active Record model when the gem loads. A page is an ordinary relation, so it chains with `where`, `order` and `includes`, and it is still lazy. Version 1.2.2 is the current release. ## The controller ```ruby class ListingsController < ApplicationController def index @listings = Listing.where(status: "open") .order(posted_at: :desc) .page(params[:page]).per(20) end end ``` 1. `page(params[:page])` sets `LIMIT` to the default size (25) and `OFFSET` to `25 * (page - 1)`. `nil`, `"abc"`, `"0"` and `"-3"` all become page 1. 2. `per(20)` replaces the limit and recomputes the offset for the same page number. It exists **only on the relation that `page` returns**, so `Listing.per(20)` is a `NoMethodError`, and it overrides any `limit` set earlier. 3. Always add an `order`. `OFFSET` over an unordered relation leaves the row order to the database, and pages can overlap. ## The arithmetic The offset for page *p* at size *n* is `n * (p - 1)`: page 3 at 20 per page is `LIMIT 20 OFFSET 40`. `page` first computes it with the default size, and `per` recomputes it, keeping the page number, from the offset and limit already on the relation. That is why the chain reads `page(...).per(...)`: `per` needs a page to adjust. `per` also replaces a `limit` applied earlier in the chain. To drop the paging again, `except(:limit, :offset)` gives back an unpaged relation. ## What the paginated relation knows | method | page 2 of 312 listings, 20 per page | |---|---| | `current_page` | 2 | | `limit_value` | 20 | | `total_count` | 312 (runs a COUNT) | | `total_pages` | 16 | | `prev_page` / `next_page` | 1 / 3 (nil at the edges) | | `first_page?` / `last_page?` | false / false | | `out_of_range?` | false | ## The view ```erb <%= render @listings %> <%= page_entries_info @listings %> <%= paginate @listings %> ``` - `paginate` renders a `<nav class="pagination">` with "First" and "Prev" links, up to **4 numbered pages on each side** of the current one (`window: 4`), `…` gaps, then "Next" and "Last". It hides the edge links on the first and last page. - Links keep the request's other params, such as a `?q=rails` search, and drop `page` on the link to page 1 (`params_on_first_page` defaults to false). - With a single page `paginate` returns `nil`, so `<%= paginate(@listings) || "All listings shown" %>` works as a fallback. - `page_entries_info` uses the model's human name ("listings") and the `helpers.page_entries_info` I18n keys. - `link_to_next_page @listings, "Older listings"` and `link_to_previous_page` render just one link each. ## Defaults worth knowing - `default_per_page` is **25**, and the model macro `paginates_per 20` changes it for one model. - `max_per_page` is **nil**, meaning no cap on `per`. - `param_name` is `:page`. `page_method_name` is `:page` too; rename it when a model already has its own `page` method. - `bin/rails generate kaminari:config` writes `config/initializers/kaminari_config.rb` with every setting commented out. ## Edge cases - **Out of range**: `?page=999` simply gives an empty relation. `out_of_range?` is true, `next_page` and `prev_page` are nil, and the default partial hides Next/Last. Kaminari never raises for it. - **Padding**: `padding(3)` shifts every page's offset by 3 rows and subtracts them in `total_pages` and `current_page`. A negative value raises `ArgumentError`. - **Arrays**: `Kaminari.paginate_array(results).page(params[:page])` wraps a plain Array so `paginate` accepts it. - **External results**: when a search service returns one page plus a total, `Kaminari.paginate_array(page_rows, total_count: 145).page(params[:page]).per(10)` lets the same `paginate` call draw links for rows Active Record never loaded. ## Common mistakes - Calling `per` on the model instead of after `page`. - Expecting 20 rows by default (that is another gem's number; Kaminari's is 25). - Forgetting the `order`, then chasing rows that appear on two pages. - Assuming the links are free: `paginate` needs a total, which on Active Record usually means a `COUNT` query.

  • The job board shows the three newest listings as a featured block above the list. How can Kaminari keep them out of the paged results?
    Chain `padding(3)`: `Listing.order(posted_at: :desc).page(params[:page]).per(20).padding(3)` adds 3 to every page's offset, so page 1 starts at the fourth listing. `total_pages` and `current_page` subtract the padding, so the links stay consistent. A negative padding raises `ArgumentError`.
  • With Kaminari, what happens for ?page=999 when only 16 pages exist?
    Nothing exceptional: `page(999)` is just a larger `OFFSET`, so the relation returns no rows. `out_of_range?` is true, `next_page` and `prev_page` return nil, and the default paginator partial hides the Next and Last links. If the product wants a redirect, the controller has to check `@listings.out_of_range?` itself.

  • Calls Listing.per(20) on the model, without page first.
  • Expects 20 rows per page by default; Kaminari's default_per_page is 25.
  • Believes Kaminari raises an error when the page is past the last one.
  • Assumes paginate's numbered links never need an extra COUNT query.
  • Paginates an unordered relation and blames Kaminari for duplicate rows.
open as a page

On a Kaminari-paginated job board with a per-page selector, how do you stop ?per=100000 loading the whole table, and where can the cap live?

level: middleimportance: should knowfreq 34%

basics

~10 s

Kaminari applies no cap by default, so per(params[:per]) passes any number to LIMIT. Set max_paginates_per 100 on the model, config.max_per_page in Kaminari.configure, or per(n, max_per_page: 100); larger requests are silently clamped.

open as a page

With Kaminari, what does without_count change about the queries Listing.page(n) runs, and which view helpers stop working with it?

level: middleimportance: should knowfreq 30%

basics

~10 s

without_count drops the COUNT query: Kaminari loads limit + 1 rows to tell whether a next page exists. total_count then raises, so paginate and page_entries_info fail; link_to_prev_page and link_to_next_page still work.

open as a page

On a job board with millions of listings, what COUNT does Kaminari's total_count run for paginate @listings, and how would you keep it affordable?

level: seniorimportance: should knowfreq 26%

basics

~20 s

total_count runs COUNT(*) over the relation without its limit, offset and order, once per relation object. Keep it affordable with indexes on the filters, max_pages to bound it, a precomputed total_pages: for paginate, or without_count.

open as a page

With Kaminari in a Rails app, how do you customise the pagination markup with rails g kaminari:views, and how does paginate select a theme?

level: middleimportance: nice to knowfreq 18%

basics

~10 s

bin/rails generate kaminari:views default copies the gem's paginator partials into app/views/kaminari for editing; another THEME name downloads that theme from the kaminari_themes GitHub repository. paginate @listings, theme: 'job_board' renders app/views/kaminari/job_board/ instead.

open as a page