Docs Menu

Docs HomeMongoid

Nested Attributes

On this page

  • Behavior

Nested attributes provide a mechanism for updating documents and their associations 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.

Nested attributes can be enabled for any association, embedded or referenced. To enable this for an association, simply provide the association 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 association, Mongoid will automatically enable autosave for that association.

When an association 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 association 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=.

←  Persistence ConfigurationCallbacks →

On this page