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

Defined in:
build/mongoid-7.3/lib/mongoid/attributes/nested.rb

Overview

Since:

  • 1.0.0

Constant Summary collapse

REJECT_ALL_BLANK_PROC =

Since:

  • 1.0.0

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

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

  • *args (Hash)

    a customizable set of options

Since:

  • 1.0.0



50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
# File 'build/mongoid-7.3/lib/mongoid/attributes/nested.rb', line 50

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
          options = options.merge!(:class_name => self.send(association.inverse_type))
        end
        association.nested_builder(attrs, options).build(self)
      end
    end
  end
end