Class: Compony::ModelFields::Association

Inherits:
Base
  • Object
show all
Defined in:
lib/compony/model_fields/association.rb

Instance Attribute Summary

Attributes inherited from Base

#extra_attrs, #model_class, #name, #schema_key

Instance Method Summary collapse

Methods inherited from Base

#association?, #label, #multi?, #transform_and_join

Constructor Details

#initializeAssociation

Returns a new instance of Association.



4
5
6
7
# File 'lib/compony/model_fields/association.rb', line 4

def initialize(...)
  super
  resolve_association!
end

Instance Method Details

#resolve_association!Object (protected)

Uses Rails methods to figure out the arity, schema key etc. and store them. This can be auto-inferred without accessing the database.



47
48
49
50
51
52
53
54
55
# File 'lib/compony/model_fields/association.rb', line 47

def resolve_association!
  @association = true
  association_info = @model_class.reflect_on_association(@name) || fail("Association #{@name.inspect} does not exist for #{@model_class.inspect}.")
  @multi = association_info.macro == :has_many
  id_name = "#{@name.to_s.singularize}_id"
  @schema_key = @multi ? id_name.pluralize.to_sym : id_name.to_sym
rescue ActiveRecord::NoDatabaseError
  Rails.logger.warn('Warning: Compony could not auto-detect fields due to missing database. This is ok when running db:create.')
end

#schema_lineObject



20
21
22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/compony/model_fields/association.rb', line 20

def schema_line
  local_schema_key = @schema_key # Capture schema_key as it will not be available within the lambda
  if multi?
    return proc do
      ary? local_schema_key do
        list :integer, cast_str: true
      end
    end
  else
    return proc do
      int? local_schema_key, cast_str: true
    end
  end
end

#simpleform_input(form, _component, name: nil, **input_opts) ⇒ Object



35
36
37
# File 'lib/compony/model_fields/association.rb', line 35

def simpleform_input(form, _component, name: nil, **input_opts)
  return form.association name || @name, **input_opts
end

#simpleform_input_hidden(form, _component, name: nil, **input_opts) ⇒ Object



39
40
41
# File 'lib/compony/model_fields/association.rb', line 39

def simpleform_input_hidden(form, _component, name: nil, **input_opts)
  return form.input name || @schema_key, as: :hidden, **input_opts
end

#value_for(data, link_to_component: nil, link_opts: {}, controller: nil) ⇒ Object



9
10
11
12
13
14
15
16
17
18
# File 'lib/compony/model_fields/association.rb', line 9

def value_for(data, link_to_component: nil, link_opts: {}, controller: nil)
  if link_to_component
    fail('Must pass controller if link_to_component is given.') unless controller
    return transform_and_join(data.send(@name), controller:) do |el|
      el.nil? ? nil : controller.helpers.compony_link(link_to_component, el, **link_opts)
    end
  else
    return transform_and_join(data.send(@name), controller:) { |el| el&.label }
  end
end