Method: Mongoid::Association::Nested::Many#build

Defined in:
lib/mongoid/association/nested/many.rb

#build(parent, options = {}) ⇒ Array

Builds the association depending on the attributes and the options passed to the macro.

This attempts to perform 3 operations, either one of an update of the existing association, a replacement of the association with a new document, or a removal of the association.

It raises an argument error if the attributes are not a Hash or an Array of key/value pairs.

Examples:

Build the nested attrs.

many.build(person)

Parameters:

  • parent (Document)

    The parent document of the association.

  • options (Hash) (defaults to: {})

    The options.

Returns:

  • (Array)

    The attributes.



30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/mongoid/association/nested/many.rb', line 30

def build(parent, options = {})
  @existing = parent.send(association.name)
  if over_limit?(attributes)
    raise Errors::TooManyNestedAttributeRecords.new(existing, options[:limit])
  end
  attributes.each do |attrs|
    if attrs.is_a?(::Hash)
      process_attributes(parent, attrs.with_indifferent_access)
    elsif attrs.is_a?(Array) && attrs.length > 1 && attrs[1].respond_to?(:with_indifferent_access)
      process_attributes(parent, attrs[1].with_indifferent_access)
    elsif attrs.is_a?(Array) && attrs.length.even?
      process_attributes(parent, Hash[*attrs].with_indifferent_access)
    else
      raise ArgumentError, "Attributes for nested association '#{association.name}' must be a Hash or an Array of key/value pairs."
    end
  end
end