Class: ActiveType::NestedAttributes::NestsManyAssociation

Inherits:
Association
  • Object
show all
Defined in:
lib/active_type/nested_attributes/nests_many_association.rb

Instance Method Summary collapse

Methods inherited from Association

#initialize, #save, #validate

Constructor Details

This class inherits a constructor from ActiveType::NestedAttributes::Association

Instance Method Details

#assign_attributes(parent, attributes_collection) ⇒ Object



9
10
11
12
13
14
15
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
45
46
# File 'lib/active_type/nested_attributes/nests_many_association.rb', line 9

def assign_attributes(parent, attributes_collection)
  return if attributes_collection.nil?

  unless attributes_collection.is_a?(Hash) || attributes_collection.is_a?(Array)
    raise ArgumentError, "Hash or Array expected, got #{attributes_collection.class.name} (#{attributes_collection.inspect})"
  end

  new_records = []

  if attributes_collection.is_a?(Hash)
    keys = attributes_collection.keys
    attributes_collection = if keys.include?('id') || keys.include?(:id)
      Array.wrap(attributes_collection)
    else
      attributes_collection.sort_by { |i, _| i.to_i }.map { |_, attributes| attributes }
    end
  end

  attributes_collection.each do |attributes|
    attributes = attributes.with_indifferent_access
    next if reject?(parent, attributes)

    destroy = truthy?(attributes.delete(:_destroy)) && @allow_destroy

    if id = attributes.delete(:id)
      child = fetch_child(parent, id)
      if destroy
        child.mark_for_destruction
      else
        child.attributes = attributes
      end
    elsif !destroy
      new_records << build_child(parent, attributes)
    end
  end

  add_children(parent, new_records)
end