Module: ConcernsOnRails::Controllers::Filterable
- Extended by:
- ActiveSupport::Concern
- Defined in:
- lib/concerns_on_rails/controllers/filterable.rb
Overview
Declarative URL-param filtering for index actions. Three modes per filter:
filter_by :status, :category # ?status=draft -> .where(status: 'draft')
filter_by :published, scope: :published # ?published=1 -> .published
filter_by :q, with: ->(rel, v) { rel.where(...) } # ?q=foo -> lambda is called
Usage:
class ArticlesController < ApplicationController
include ConcernsOnRails::Controllers::Filterable
filter_by :status
filter_by :q, with: ->(rel, v) { rel.where("title ILIKE ?", "%#{v}%") }
def index
render json: filtered(Article.all)
end
end
Instance Method Summary collapse
-
#filtered(relation) ⇒ Object
Apply all declared filters to a relation based on params.
Instance Method Details
#filtered(relation) ⇒ Object
Apply all declared filters to a relation based on params. Blank values are skipped so unset filters don’t narrow the relation.
46 47 48 49 50 51 52 53 54 |
# File 'lib/concerns_on_rails/controllers/filterable.rb', line 46 def filtered(relation) self.class.filterable_rules.each do |field, | value = params[field] next if value.blank? relation = apply_filter(relation, field, value, ) end relation end |