Class: RESTFramework::ModelQueryFilter
- Inherits:
-
BaseFilter
- Object
- BaseFilter
- RESTFramework::ModelQueryFilter
- Defined in:
- lib/rest_framework/filters/model_query.rb
Overview
A simple filtering backend that supports filtering a recordset based on query parameters.
Instance Method Summary collapse
-
#_get_fields ⇒ Object
Get a list of filterset fields for the current action.
-
#_get_filter_params ⇒ Object
Filter params for keys allowed by the current action’s filterset_fields/fields config.
-
#get_filtered_data(data) ⇒ Object
Filter data according to the request query parameters.
Methods inherited from BaseFilter
Constructor Details
This class inherits a constructor from RESTFramework::BaseFilter
Instance Method Details
#_get_fields ⇒ Object
Get a list of filterset fields for the current action.
4 5 6 7 |
# File 'lib/rest_framework/filters/model_query.rb', line 4 def _get_fields # Always return a list of strings; `@controller.get_fields` already does this. return @controller.class.filterset_fields&.map(&:to_s) || @controller.get_fields end |
#_get_filter_params ⇒ Object
Filter params for keys allowed by the current action’s filterset_fields/fields config.
10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
# File 'lib/rest_framework/filters/model_query.rb', line 10 def _get_filter_params fields = self._get_fields return @controller.request.query_parameters.select { |p, _| # Remove any trailing `__in` from the field name. field = p.chomp("__in") # Remove any associations whose sub-fields are not filterable. if match = /(.*)\.(.*)/.match(field) field, sub_field = match[1..2] next false unless field.in?(fields) sub_fields = @controller.class.get_field_config(field)[:sub_fields] || [] next sub_field.in?(sub_fields) end next field.in?(fields) }.map { |p, v| # Convert fields ending in `__in` to array values. if p.end_with?("__in") p = p.chomp("__in") v = v.split(",") end # Convert "nil" and "null" to nil. if v == "nil" || v == "null" v = nil end [p, v] }.to_h.symbolize_keys end |
#get_filtered_data(data) ⇒ Object
Filter data according to the request query parameters.
44 45 46 47 48 49 50 |
# File 'lib/rest_framework/filters/model_query.rb', line 44 def get_filtered_data(data) if filter_params = self._get_filter_params.presence return data.where(**filter_params) end return data end |