Navigation

Nested Attributes

Nested attributes provide a mechanism for updating documents and their relations in a single operation by nesting attributes in a single parameters hash. This is useful when wanting to edit multiple documents within a single web form.

Behavior

Nested attributes can be enabled for any relation, embedded or referenced. To enable this for the relation, simply provide the relation name to the accepts_nested_attributes_for macro.

class Band
  include Mongoid::Document
  embeds_many :albums
  belongs_to :producer
  accepts_nested_attributes_for :albums, :producer
end

Note that when you add nested attributes functionality to a referenced relation, Mongoid will automatically enable autosave for that relation.

When a relation gains nested attributes behavior, an additional method is added to the base model, which should be used to update the attributes with the new functionality. This method is the relation name plus _attributes=. You can use this method directly, or more commonly the name of the method can be an attribute in the updates for the base class, in which case Mongoid will call the appropriate setter under the covers.

band = Band.first
band.producer_attributes = { name: "Flood" }
band.attributes = { producer_attributes: { name: "Flood" }}

Note that this will work with any attribute based setter method in Mongoid. This includes: update_attributes, update_attributes! and attributes=.

←   Relations Callbacks  →