Module: ConcernsOnRails::Controllers::Sortable
- Extended by:
- ActiveSupport::Concern
- Defined in:
- lib/concerns_on_rails/controllers/sortable.rb
Overview
URL-param-driven ordering for index actions, with a strict allow-list to prevent ordering by arbitrary user-supplied columns (SQL injection / data exposure risk).
class ArticlesController < ApplicationController
include ConcernsOnRails::Controllers::Sortable
sortable_by :created_at, :title, :published_at, default: :created_at, direction: :desc
def index
render json: sorted(Article.all)
end
end
Reads params and params. Falls back to the configured defaults if either is missing or invalid.
Constant Summary collapse
- VALID_DIRECTIONS =
%i[asc desc].freeze
Instance Method Summary collapse
Instance Method Details
#sorted(relation) ⇒ Object
46 47 48 49 50 51 52 53 54 55 56 |
# File 'lib/concerns_on_rails/controllers/sortable.rb', line 46 def sorted(relation) fields = sort_fields return relation if fields.empty? # reorder (not order) so the user-requested columns REPLACE any prior # ORDER BY — including a model default_scope order. Multiple whitelisted # columns (comma-separated in params[:sort]) are applied in request order. direction = sort_direction ordering = fields.to_h { |field| [field, direction] } relation.reorder(ordering) end |