Module: Mongoid::NestedAttributes::ClassMethods

Defined in:
lib/mongoid/nested_attributes.rb

Constant Summary collapse

REJECT_ALL_BLANK_PROC =
->(attributes){
  attributes.all? { |key, value| key == '_destroy' || value.blank? }
}

Instance Method Summary collapse

Instance Method Details

#accepts_nested_attributes_for(*args) ⇒ Object

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

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 (Array<Symbol>, Hash)

    A list of relation names, followed by a hash of options.



42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# File 'lib/mongoid/nested_attributes.rb', line 42

def accepts_nested_attributes_for(*args)
  options = args.extract_options!
  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
     = relations[name.to_s]
    raise Errors::NestedAttributesMetadataNotFound.new(self, name) unless 
    autosave_nested_attributes()
    re_define_method(meth) do |attrs|
      _assigning do
        .nested_builder(attrs, options).build(self, mass_assignment_options)
      end
    end
  end
end