Simple Pagination Concern for Ruby on Rails
This is a reusable pagination concern that provides a simple solution for pagination in a Ruby on Rails application.
Some of the code comes from Jonathan Allard who originally shared it here. However, I came across issues with the original code when specifying which page should be displayed. Rails would change up the order of the records resulting in incorrect ordering when paging through results – essentially breaking the pagination functionality. Adding in order_by
and order_direction
resolves the issue and also adds ordering functionality to the concern.
Here is the working code:
# app/controllers/concerns/pagination.rb
module Pagination
extend ActiveSupport::Concern
def default_per_page
25
end
def page_num
params.fetch(:page, 1).to_i
end
def per_page
params.fetch(:per_page, 25).to_i
end
def paginate_offset
(page_num - 1) * per_page
end
def order_by
params.fetch(:order_by, :id)
end
def order_direction
params.fetch(:order_direction, :asc)
end
def paginate
->(it) { it.limit(per_page).offset(paginate_offset).order("#{order_by}": order_direction) }
end
end
Include it in your ApplicationController to make it available from any controller.
ActionController::Base
include Pagination
end
It can then be used like this in your controllers:
def index
records = Record.all
records.then(&paginate)
end
In this example the default results per page is set to 25, however, this can be modified in the code or a per_page
parameter can be passed to override the default.
GET /records?page=&per_page=100