Class: Uchi::Field::HasMany

Inherits:
Field
  • Object
show all
Defined in:
app/components/uchi/field/has_many.rb

Defined Under Namespace

Classes: Edit, Index, Show

Constant Summary collapse

DEFAULT_COLLECTION_QUERY =
->(query) { query }.freeze

Instance Method Summary collapse

Constructor Details

#initialize(name) ⇒ HasMany

Returns a new instance of HasMany.



111
112
113
114
# File 'app/components/uchi/field/has_many.rb', line 111

def initialize(name)
  super
  @collection_query = DEFAULT_COLLECTION_QUERY
end

Instance Method Details

#collection_query(query_proc = Configuration::Unset) ⇒ self, Proc

Sets or gets a custom query for filtering the collection of associated records.

When called with an argument, sets the query and returns self for chaining. When called without arguments, returns the current query.

Examples:

Setting

Field::HasMany.new(:users).collection_query(->(query) {
  query.where(active: true)
})

Getting

field.collection_query # => #<Proc...>

Parameters:

  • query_proc (Proc, Symbol) (defaults to: Configuration::Unset)

    A callable that receives an ActiveRecord query and returns a modified query.

Returns:

  • (self, Proc)

    Returns self for method chaining when setting, or the query proc when getting



133
134
135
136
137
138
# File 'app/components/uchi/field/has_many.rb', line 133

def collection_query(query_proc = Configuration::Unset)
  return @collection_query if query_proc == Configuration::Unset

  @collection_query = query_proc
  self
end

#group_as(_action) ⇒ Object



140
141
142
# File 'app/components/uchi/field/has_many.rb', line 140

def group_as(_action)
  :associations
end

#param_keyObject



144
145
146
147
148
# File 'app/components/uchi/field/has_many.rb', line 144

def param_key
  # TODO: This is too naive. We need to match this to the actual foreign
  # key of the model.
  :"#{name.to_s.singularize}_ids"
end

#permitted_paramObject



150
151
152
# File 'app/components/uchi/field/has_many.rb', line 150

def permitted_param
  {param_key => []}
end