Module: Filterameter::DeclarativeFilters

Extended by:
ActiveSupport::Concern
Includes:
Filterable, Sortable
Defined in:
lib/filterameter/declarative_filters.rb

Overview

# Declarative Controller Filters

Mixin DeclarativeFilters should be included in controllers to enable the filter DSL.

Instance Method Summary collapse

Instance Method Details

#build_query_from_filters(starting_query = nil) ⇒ Object

Returns an ActiveRecord query from the filter parameters.

def index
  @widgets = build_query_from_filters
end

The method optionally takes a starting query. For example, this restricts the results to only active widgets:

def index
  @widgets = build_query_from_filters(Widgets.where(active: true))
end

The starting query can also be used to provide eager loading:

def index
  @widgets = build_query_from_filters(Widgets.includes(:manufacturer))
end


47
48
49
# File 'lib/filterameter/declarative_filters.rb', line 47

def build_query_from_filters(starting_query = nil)
  self.class.filter_coordinator.build_query(filter_parameters, starting_query)
end

#filter_parametersObject



51
52
53
54
55
56
57
58
59
# File 'lib/filterameter/declarative_filters.rb', line 51

def filter_parameters
  filter_key = Filterameter.configuration.filter_key

  if filter_key
    params.to_unsafe_h.fetch(filter_key, {})
  else
    params.to_unsafe_h.slice(*self.class.filter_coordinator.filter_parameter_names, :sort)
  end
end