In a Rails app using Kaminari, how do you paginate job listings with page and per, and render the page links in the view?
answer
- a class method on every model
- page(params[:page]), then per
- 25 per page by default
- paginate @listings in the view
- page_entries_info for the summary
basics
~20 sCall 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 sKaminari 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 linesclass ListingsController < ApplicationController
def index
@listings = Listing.order(posted_at: :desc).page(params[:page]).per(20)
end
endgo deeper
Recall page(params[:page]).per(n) in the controller, paginate and page_entries_info in the view, and the default of 25 per page.
Explain why per only exists after page, what LIMIT and OFFSET page builds, and that paginate usually needs a COUNT for its links.
Handle the edges: out-of-range pages, padding for featured rows, a stable order, and the COUNT cost on big tables.
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.