Class: Mongoid::Association::Nested::One

Inherits:
Object
  • Object
show all
Includes:
Buildable
Defined in:
lib/mongoid/association/nested/one.rb

Overview

Builder class used to perform #accepts_nested_attributes_for attribute assignment on one-to-n associations.

Instance Attribute Summary collapse

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) ⇒ One

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

Examples:

Instantiate the builder.

One.new(association, attributes)

Parameters:

  • association (Mongoid::Association::Relatable)

    The association metadata.

  • attributes (Hash)

    The attributes hash to attempt to set.

  • options (Hash)

    The options defined.



52
53
54
55
56
57
58
# File 'lib/mongoid/association/nested/one.rb', line 52

def initialize(association, attributes, options)
  @attributes = attributes.with_indifferent_access
  @association = association
  @options = options
  @class_name = options[:class_name] ? options[:class_name].constantize : association.klass
  @destroy = @attributes.delete(:_destroy)
end

Instance Attribute Details

#destroyObject

Returns the value of attribute destroy.



13
14
15
# File 'lib/mongoid/association/nested/one.rb', line 13

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:



28
29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/mongoid/association/nested/one.rb', line 28

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