Module: Orderable
- Extended by:
- ActiveSupport::Concern
- Included in:
- Apicasso::CrudController
- Defined in:
- app/controllers/concerns/orderable.rb
Overview
This concern is used to provide abstract ordering based on ‘params`
Constant Summary collapse
- SORT_ORDER =
{ '+' => :asc, '-' => :desc }.freeze
Instance Method Summary collapse
-
#ordering_params(params) ⇒ Object
A list of the param names that can be used for ordering the model list.
Instance Method Details
#ordering_params(params) ⇒ Object
A list of the param names that can be used for ordering the model list
9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 |
# File 'app/controllers/concerns/orderable.rb', line 9 def ordering_params(params) # For example it retrieves a list of orders in descending order of total_value. # Within a specific total_value, older orders are ordered first # # GET /orders?sort=-total_value,created_at # ordering_params(params) # => { total_value: :desc, created_at: :asc } # # Usage: # Order.order(ordering_params(params)) ordering = {} params[:sort]&.delete(' ').try(:split, ',').try(:each) do |attr| parsed_attr = parse_attr attr if model.attribute_names.include?(parsed_attr) ordering[parsed_attr] = SORT_ORDER[parse_sign attr] end end ordering end |