Module: Mongoid::Attributes::ClassMethods

Defined in:
lib/mongoid/attributes.rb

Instance Method Summary collapse

Instance Method Details

#accepts_nested_attributes_for(*args) ⇒ Object

Defines attribute setters for the associations specified by the names. This will work for a has one or has many association.

Example:

class Person < Mongoid::Document
  has_one :name
  has_many :addresses

  accepts_nested_attributes_for :name, :addresses
end


118
119
120
121
122
123
124
125
126
127
128
129
# File 'lib/mongoid/attributes.rb', line 118

def accepts_nested_attributes_for(*args)
  associations = args.flatten
  options = associations.last.is_a?(Hash) ? associations.pop : {}
  associations.each do |name|
    define_method("#{name}_attributes=") do |attrs|
      reject(attrs, options)
      association = send(name)
      update(association, true)
      association.nested_build(attrs)
    end
  end
end