ruby
41 lines · 8 steps
A reusable pagination concern in Rails
A controller concern that safely paginates any scope and exposes page metadata through response headers.
Explained by
highlit
1module Paginatable
2 extend ActiveSupport::Concern
3
4 private
5
6 def paginate(scope)
7 page = params.fetch(:page, 1).to_i
8 per_page = [params.fetch(:per_page, 25).to_i, 100].min
9 per_page = 25 if per_page < 1
10
11 total = scope.count
12 total_pages = (total.to_f / per_page).ceil
13 page = page.clamp(1, [total_pages, 1].max)
14
15 records = scope.limit(per_page).offset((page - 1) * per_page)
16
17 set_pagination_headers(page, per_page, total, total_pages)
18 records
19 end
20
21 def set_pagination_headers(page, per_page, total, total_pages)
22 response.set_header("X-Total-Count", total.to_s)
23 response.set_header("X-Total-Pages", total_pages.to_s)
24 response.set_header("X-Page", page.to_s)
25 response.set_header("X-Per-Page", per_page.to_s)
26
27 links = {
28 first: page_url(1, per_page),
29 prev: (page > 1 ? page_url(page - 1, per_page) : nil),
30 next: (page < total_pages ? page_url(page + 1, per_page) : nil),
31 last: page_url([total_pages, 1].max, per_page)
32 }.compact
33
34 header = links.map { |rel, url| %(<#{url}>; rel="#{rel}") }.join(", ")
35 response.set_header("Link", header) if header.present?
36 end
37
38 def page_url(page, per_page)
39 url_for(request.query_parameters.merge(page: page, per_page: per_page, only_path: false))
40 end
41end
01 / 01
STEP 01
‹ swipe to step through ›
Walkthrough
Space play
←→ step
click any line
Three takeaways
- 1Clamping and capping user-supplied paging params guards against absurd offsets and unbounded page sizes.
- 2Emitting pagination state as response headers keeps JSON payloads clean and API-friendly.
- 3Wrapping the logic in a concern lets any controller paginate an ActiveRecord scope with one call.
Related explainers
ruby
class ToastBroadcaster include ActionView::RecordIdentifier def self.broadcast_to(user, message:, type: :notice)
How Turbo Stream toasts broadcast in Rails
turbo-streams
service-object
real-time
Intermediate
6 steps
ruby
class TemplateInterpolator PLACEHOLDER = /\{\{\s*([\w.]+)\s*\}\}/ def initialize(strict: false)
Interpolating templates with dotted keys in Ruby
regex
string-interpolation
hash-traversal
Intermediate
6 steps
ruby
class KeyTransformer def self.camelize(data) new.camelize(data) end
Recursively camelizing nested Ruby data
recursion
data-transformation
pattern-matching
Intermediate
7 steps
ruby
class Api::MessagesController < ApiController before_action :authenticate_api_key! rate_limit to: 100,
Layered API rate limiting in Rails
rate-limiting
api-authentication
throttling
Intermediate
9 steps
ruby
class Order < ApplicationRecord include AASM belongs_to :warehouse
Modeling an order lifecycle with AASM in Rails
state machine
guards
callbacks
Intermediate
10 steps
ruby
require "timeout" require "net/http" class RemoteInventoryClient
Bounding a slow HTTP call with Timeout in Ruby
timeout
error-handling
http
Intermediate
6 steps
Share this explainer
Here's the card — post it anywhere.
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code
Embed this explainer
Drop the interactive walkthrough into a blog or docs. Views never cost a credit.
<iframe src="https://highlit.co/explainers/a-reusable-pagination-concern-in-rails-explained-ruby-0c3b/embed?autoplay=1" width="100%" height="520" loading="lazy" style="border:0"></iframe>
Autoplay is on by default — add ?autoplay=0 to start paused.