Class: Mongoid::Association::Referenced::NestedAttributes::One

Inherits:
NestedBuilder
  • Object
show all
Defined in:
build/mongoid-8.1/lib/mongoid/association/referenced/has_one/nested_builder.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(association, attributes, options) ⇒ One

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

Examples:

Instantiate the builder.

One.new(association, attributes)

Parameters:

  • association (Association)

    The association metadata.

  • attributes (Hash)

    The attributes hash to attempt to set.

  • options (Hash)

    The options defined.



46
47
48
49
50
51
# File 'build/mongoid-8.1/lib/mongoid/association/referenced/has_one/nested_builder.rb', line 46

def initialize(association, attributes, options)
  @attributes = attributes.with_indifferent_access
  @association = association
  @options = options
  @destroy = @attributes.delete(:_destroy)
end

Instance Attribute Details

#destroyObject

Returns the value of attribute destroy.



9
10
11
# File 'build/mongoid-8.1/lib/mongoid/association/referenced/has_one/nested_builder.rb', line 9

def destroy
  @destroy
end

Instance Method Details

#build(parent) ⇒ Document

Note:

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.

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

Examples:

Build a 1-1 nested document.

one.build(person, as: :admin)

Parameters:

  • parent (Document)

    The parent document.

Returns:



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

def build(parent)
  return if reject?(parent, attributes)
  @existing = parent.send(association.name)
  if update?
    attributes.delete_id
    existing.assign_attributes(attributes)
  elsif replace?
    parent.send(association.setter, Factory.build(association.klass, attributes))
  elsif delete?
    parent.send(association.setter, nil)
  end
end