123456789_123456789_123456789_123456789_123456789_

Module: Mongoid::Attributes::Nested::ClassMethods

Relationships & Source Files
Extension / Inclusion / Inheritance Descendants
Extended In:
Defined in: lib/mongoid/attributes/nested.rb

Constant Summary

Instance Method Summary

Instance Method Details

#accepts_nested_attributes_for(*args)

Used when needing to update related models from a parent association. Can be used on embedded or referenced associations.

Examples:

Defining nested attributes.

class Person
  include Mongoid::Document

  embeds_many :addresses
  embeds_one :game
  references_many :posts

  accepts_nested_attributes_for :addresses, :game, :posts
end

Parameters:

  • *args (Symbol..., Hash)

    A list of association names, followed by an optional hash of options.

[ GitHub ]

  
# File 'lib/mongoid/attributes/nested.rb', line 48

def accepts_nested_attributes_for(*args)
  options = args.extract_options!.dup
  options[:autosave] = true if options[:autosave].nil?

  options[:reject_if] = REJECT_ALL_BLANK_PROC if options[:reject_if] == :all_blank
  args.each do |name|
    meth = "#{name}_attributes="
    self.nested_attributes["#{name}_attributes"] = meth
    association = relations[name.to_s]
    raise Errors::NestedAttributesMetadataNotFound.new(self, name) unless association
    autosave_nested_attributes(association) if options[:autosave]

    re_define_method(meth) do |attrs|
      _assigning do
        if association.polymorphic? and association.inverse_type
          klass = association.resolver.model_for(send(association.inverse_type))
          options = options.merge!(:class_name => klass)
        end
        association.nested_builder(attrs, options).build(self)
      end
    end
  end
end

#autosave_nested_attributes(association) (private)

This method is for internal use only.

Add the autosave information for the nested association.

Examples:

Add the autosave if appropriate.

Person.autosave_nested_attributes()

Parameters:

[ GitHub ]

  
# File 'lib/mongoid/attributes/nested.rb', line 82

def autosave_nested_attributes(association)
  # In order for the autosave functionality to work properly, the association needs to be
  # marked as autosave despite the fact that the option isn't present. Because the method
  # Association#autosave? is implemented by checking the autosave option, this is the most
  # straightforward way to mark it.
  if association.autosave? || (association.options[:autosave].nil? && !association.embedded?)
    association.options[:autosave] = true
    Association::Referenced::AutoSave.define_autosave!(association)
  end
end