Class: Dynabute::NestedAttributes::Builder

Inherits:
Object
  • Object
show all
Defined in:
lib/dynabute/nested_attributes.rb

Instance Method Summary collapse

Constructor Details

#initialize(attributes_list, dynabutee) ⇒ Builder

Returns a new instance of Builder.



7
8
9
10
11
12
13
14
# File 'lib/dynabute/nested_attributes.rb', line 7

def initialize(attributes_list, dynabutee)
  unless attributes_list.is_a?(Hash) || attributes_list.is_a?(Array)
    raise ArgumentError, "Hash or Array expected, got #{attributes_list.class.name} (#{attributes_list.inspect})"
  end
  @attributes_list = normalize_attributes(attributes_list)
  @nested_attributes_to_assign = {}
  @dynabutee = dynabutee
end

Instance Method Details

#build_assignable_attributes {|@nested_attributes_to_assign| ... } ⇒ Object

Yields:

  • (@nested_attributes_to_assign)


16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/dynabute/nested_attributes.rb', line 16

def build_assignable_attributes
  desperados = [] # has_one params without :id key need special care
  collect_fields(@attributes_list)
  @attributes_list.each do |attrs|
    field = resolve_field(attrs)
    next if field.nil?
    next let_go(field, attrs) if field.has_many
    next let_go(field, attrs) if attrs[:id].present?
    desperados.push([attrs, field])
  end

  desperados
    .group_by { |(_, field)| field.value_type }
    .each do |value_type, attrs_fields| # for each value tables

    existing_values = @dynabutee.send(Util.value_relation_name(value_type))
                        .where(field_id: attrs_fields.map{|(_, f)| f.id})
                        .to_a # trying to reduce queries
    attrs_fields.each do |(attrs, field)| # for each attrs
      params = {
        id: existing_values.detect{|v| v.field_id == field.id}.try(:id),
        value: attrs[:value],
        field_id: field.id
      }
      let_go(field, params)
    end
  end
  yield(@nested_attributes_to_assign)
end