Class: Uchi::Field::BelongsTo

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

Defined Under Namespace

Modules: Helpers Classes: Edit, Index, Show

Constant Summary collapse

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

Instance Method Summary collapse

Constructor Details

#initialize(name) ⇒ BelongsTo

Returns a new instance of BelongsTo.



109
110
111
112
# File 'app/components/uchi/field/belongs_to.rb', line 109

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::BelongsTo.new(:company).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



131
132
133
134
135
136
# File 'app/components/uchi/field/belongs_to.rb', line 131

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



138
139
140
# File 'app/components/uchi/field/belongs_to.rb', line 138

def group_as(_action)
  :attributes
end

#on(*actions) ⇒ Object

Returns the actions this field should appear on.

For polymorphic associations, excludes :edit and :new to prevent showing the field on forms where the type cannot be determined.



146
147
148
149
150
151
# File 'app/components/uchi/field/belongs_to.rb', line 146

def on(*actions)
  on = super
  return on - [:edit, :new] if polymorphic? && actions.empty?

  on
end

#param_keyObject



153
154
155
156
157
# File 'app/components/uchi/field/belongs_to.rb', line 153

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