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
  include Mongoid::Document
  embeds_one :name
  embeds_many :addresses

  accepts_nested_attributes_for :name, :addresses
end


186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
# File 'lib/mongoid/attributes.rb', line 186

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)
      if association
        observe(association, true)
        association.nested_build(attrs)
      else
        send("build_#{name}", attrs)
      end
    end
  end
end