With Kaminari, what does without_count change about the queries Listing.page(n) runs, and which view helpers stop working with it?
answer
- no SELECT COUNT at all
- loads limit + 1 rows
- last_page? from the extra row
- total_count raises
- link_to_prev_page and link_to_next_page
basics
~10 swithout_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.
solid answer
~40 sNormally `paginate @listings` calls `total_count`, which runs a `SELECT COUNT(*)` over the relation minus its limit, offset and order, beside the page query. `Listing.order(posted_at: :desc).page(params[:page]).without_count` extends the relation so that loading it fetches `limit + 1` rows. If the extra row comes back, Kaminari drops it and records that a next page exists, which drives `last_page?` and `next_page`; `out_of_range?` just means the page came back empty. In exchange there is no total: `total_count` raises a `RuntimeError` telling you to use `link_to_next_page` or `link_to_previous_page`, so `paginate`, `page_entries_info` and `total_pages` cannot be used. It suits a large table browsed as newer and older pages, or a feed. Deep pages still pay `OFFSET`'s cost.
code
sql · 8 lines-- page(3).per(25), default
SELECT COUNT(*) FROM "listings" WHERE "listings"."status" = 'open';
SELECT "listings".* FROM "listings" WHERE "listings"."status" = 'open'
ORDER BY "listings"."posted_at" DESC LIMIT 25 OFFSET 50;
-- page(3).per(25).without_count
SELECT "listings".* FROM "listings" WHERE "listings"."status" = 'open'
ORDER BY "listings"."posted_at" DESC LIMIT 26 OFFSET 50;go deeper
Know that without_count removes Kaminari's COUNT query, and that you then use link_to_prev_page and link_to_next_page instead of paginate.
Explain the limit + 1 trick, how last_page? and out_of_range? are redefined, and why total_count raises instead of returning nil.
Choose it per screen, watch for size or other calls that bring a COUNT back, and know it leaves OFFSET's deep-page cost untouched.
Agree with product which lists may drop totals and numbered pages, in exchange for lower database load.
## The count `paginate` needs To draw numbered links and a Last link, Kaminari's `paginate` helper needs `total_pages`, and that needs **`total_count`**. On an Active Record relation, `total_count` runs a second query, `SELECT COUNT(*)` over the same `WHERE` without `LIMIT`, `OFFSET` and `ORDER`. On a large, filtered table that count can cost more than fetching the page itself, and it runs on every page view. ## What `without_count` changes ```ruby @listings = Listing.where(status: "open") .order(posted_at: :desc) .page(params[:page]).per(25) .without_count ``` `without_count` **extends the relation** with a module (`Kaminari::PaginatableWithoutCount`) that overrides a few methods: 1. **`load`** temporarily raises the limit by one, runs the query (`LIMIT 26 OFFSET 50` for page 3), then lowers it again. If a 26th row came back, it removes it and sets an internal "has next" flag. 2. **`last_page?`** becomes "not out of range and no extra row", so `next_page` is correct without a count. 3. **`out_of_range?`** becomes "the loaded page is empty". 4. **`total_count`** raises a `RuntimeError`: "This scope is marked as a non-count paginable scope and can't be used in combination with `#paginate' or `#page_entries_info'". The result is **one query per page** instead of two. ## Which helpers still work | helper | with `without_count` | |---|---| | `link_to_next_page`, `link_to_previous_page` (`link_to_prev_page`) | work | | `next_page_url`, `prev_page_url`, `rel_next_prev_link_tags` | work | | `current_page`, `next_page`, `prev_page`, `last_page?` | work | | `paginate` | raises, since it needs `total_pages` | | `page_entries_info` | raises, since it prints the total | | `total_count`, `total_pages` | raise | ```erb <%= render @listings %> <%= link_to_previous_page @listings, "Newer listings" %> <%= link_to_next_page @listings, "Older listings" %> ``` ## The two modes side by side | | default | `without_count` | |---|---|---| | queries per page | page select + `COUNT(*)` | one select of `limit + 1` rows | | `total_count` / `total_pages` | exact | raise | | `last_page?` | `current_page == total_pages` | no extra row came back | | `paginate`, `page_entries_info` | work | raise | | deep-page cost | `OFFSET` scan + count | `OFFSET` scan | ## An API that only links forward The same mode suits a JSON endpoint that offers a `next` link and no totals. Kaminari's URL helpers live in `Kaminari::Helpers::UrlHelper`, which a controller can include: ```ruby class Api::ListingsController < ActionController::API include Kaminari::Helpers::UrlHelper def index listings = Listing.order(posted_at: :desc).page(params[:page]).without_count render json: { listings: listings, next_url: next_page_url(listings) } end end ``` `next_page_url` returns `nil` on the last page, because `next_page` is nil once the extra row fails to appear. ## When to choose it - **Large tables where nobody needs the total**: an activity feed, a log, "older/newer" browsing of job listings. - **APIs with next links only**, where computing `total-count` on every request is not worth it. - **Infinite scroll**, where the client only asks "is there more?". Keep the count where the screen promises numbered pages, a Last link or a "312 listings" headline. There the total is the feature, not overhead. ## What it does not fix - Page 4,000 still means `OFFSET 99975`, so the database walks past every skipped row. Deep paging needs a different technique, which is outside Kaminari's scope API. - The flag is set when the relation **loads**. Iterate it, or call `load`, before asking `last_page?`; the overridden methods load it if needed. - Asking `@listings.size` before the relation is loaded makes Active Record run a `COUNT` of its own, which quietly brings back a count query. Iterate first, or use `length` on the loaded records.
- A Kaminari view with without_count calls @listings.size in a heading before the loop. Why does a COUNT query reappear in the log?`size` on an Active Record relation that has not loaded yet runs `count(:all)`, a query of its own; the `without_count` override only covers `total_count`. Render the records first, or call `load` and then `size` (which uses the loaded rows), or show no number at all.
- When would you keep the COUNT and not use without_count on the job board?When the UI promises numbered pages, a Last link or "312 listings", for example a search results page where users jump around. Then the count is the price of the feature; keep it cheap with indexes on the filtered columns, or bound it with `max_pages`.
without_count is like checking whether a book has another page by peeking at the next sheet, instead of reading the page count printed on the back cover: you learn whether there is more, but never how much.
- Calls paginate on a without_count relation and expects numbered links.
- Says without_count makes Kaminari switch from OFFSET to a WHERE on the last id.
- Thinks without_count still counts, just once per session.
- Uses page_entries_info with without_count to show the total.
- Believes without_count makes deep pages fast on huge tables.