Class: Mongoid::Association::Nested::Many

Inherits:
Object
  • Object
show all
Includes:
Buildable
Defined in:
build/mongoid-8.1/lib/mongoid/association/nested/many.rb

Instance Attribute Summary

Attributes included from Buildable

#association, #attributes, #existing, #options

Instance Method Summary collapse

Methods included from Buildable

#allow_destroy?, #convert_id, #reject?, #update_only?

Constructor Details

#initialize(association, attributes, options = {}) ⇒ Many

Create the new builder for nested attributes on one-to-many associations.

Examples:

Initialize the builder.

Many.new(association, attributes, options)

Parameters:

  • association (Association)

    The association metadata.

  • attributes (Hash)

    The attributes hash to attempt to set.

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

    The options defined.



46
47
48
49
50
51
52
53
54
55
56
57
# File 'build/mongoid-8.1/lib/mongoid/association/nested/many.rb', line 46

def initialize(association, attributes, options = {})
  if attributes.respond_to?(:with_indifferent_access)
    @attributes = attributes.with_indifferent_access.sort do |a, b|
      a[0].to_i <=> b[0].to_i
    end
  else
    @attributes = attributes
  end
  @association = association
  @options = options
  @class_name = options[:class_name] ? options[:class_name].constantize : association.klass
end

Instance Method Details

#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.

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.



23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'build/mongoid-8.1/lib/mongoid/association/nested/many.rb', line 23

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)
    else
      process_attributes(parent, attrs[1].with_indifferent_access)
    end
  end
end