Class: Plutonium::Query::Filters::Association

Inherits:
Plutonium::Query::Filter show all
Defined in:
lib/plutonium/query/filters/association.rb

Overview

Select filter for association records

Examples:

Basic - infers Category class from :category key

filter :category, with: :association

With explicit class

filter :author, with: :association, class_name: User

With multiple selection

filter :tags, with: :association, class_name: Tag, multiple: true

With custom scope

filter :user, with: :association, class_name: User, scope: ->(s) { s.active }

Instance Attribute Summary

Attributes inherited from Plutonium::Query::Filter

#key

Instance Method Summary collapse

Methods inherited from Plutonium::Query::Filter

lookup

Methods included from Definition::Presentable

#description, #icon, #label

Constructor Details

#initialize(class_name: nil, resource_class: nil, scope: nil, multiple: false) ⇒ Association

Returns a new instance of Association.



19
20
21
22
23
24
25
# File 'lib/plutonium/query/filters/association.rb', line 19

def initialize(class_name: nil, resource_class: nil, scope: nil, multiple: false, **)
  super(**)
  @class_name = class_name
  @resource_class = resource_class
  @scope_proc = scope
  @multiple = multiple
end

Instance Method Details

#apply(scope, value:) ⇒ Object



27
28
29
30
31
32
33
34
35
36
# File 'lib/plutonium/query/filters/association.rb', line 27

def apply(scope, value:)
  return scope if value.blank?

  foreign_key = :"#{key}_id"
  if @multiple && value.is_a?(Array)
    scope.where(foreign_key => value.reject(&:blank?))
  else
    scope.where(foreign_key => value)
  end
end

#customize_inputsObject



38
39
40
41
42
43
44
# File 'lib/plutonium/query/filters/association.rb', line 38

def customize_inputs
  input :value,
    as: :resource_select,
    association_class: association_class,
    multiple: @multiple,
    include_blank: @multiple ? false : "All"
end