Nested attributes
Nested attributes allow you to save attributes on associated records through the parent. By default nested attribute updating is turned off for referential associations and turned on for embed associations.
You can enable it using the accepts_nested_attributes_for class method.
When you enable nested attributes an attribute writer is defined on the model.
The attribute writer is named after the association, which means that in the following example, four new methods are added to your model:
- author_attributes=(attributes)
- pages_attributes=(attributes)
- publisher_attributes=(attributes)
- reviews_attributes=(attributes)
class Book include Mongoid::Document has_one :author has_many :pages embeds_one :publisher embeds_many :reviews accepts_nested_attributes_for :author, :pages end
Note that the :autosave option needs to be enabled for relational associations that accepts_nested_attributes_for is used for if you don't want to manually save the relation on update.
class Member include Mongoid::Document has_one :avatar, autosave: true accepts_nested_attributes_for :avatar end
One-to-one
Consider a Member model that has one Avatar:
class Member include Mongoid::Document has_one :avatar accepts_nested_attributes_for :avatar end
Enabling nested attributes on a one-to-one association allows you to create the member and avatar in one go:
params =
{ member:
{ name: "Jack", avatar_attributes: { icon: "smiling" } }
}
member = Member.create(params[:member])
member.avatar.id # => 2
member.avatar.icon # => 'smiling'
It also allows you to update the avatar through the member:
params =
{ member:
{ avatar_attributes: { id: "2", icon: "sad" } }
}
member.update_attributes(params[:member])
member.avatar.icon # => 'sad'
By default you will only be able to set and update attributes on the associated model. If you want to destroy the associated model through the attributes hash, you have to enable it first using the :allow_destroy option.
class Member include Mongoid::Document has_one :avatar accepts_nested_attributes_for :avatar, :allow_destroy => true end
Now, when you add the _destroy key to the attributes hash, with a value that evaluates to true, you will destroy the associated model:
member.avatar_attributes = { id: "2", _destroy: "1" }
member.avatar.marked_for_destruction? # => true
member.save
member.reload.avatar # => nil
Note that the model will not be destroyed until the parent is saved.
One-to-many
Consider a member that has a number of posts:
class Member include Mongoid::Document has_many :posts accepts_nested_attributes_for :posts end
You can now set or update attributes on an associated post model through the attribute hash.
For each hash that does not have an id key a new record will be instantiated, unless the hash also contains a _destroy key that evaluates to true.
params = { member: {
name: "joe", posts_attributes: [
{ title: "Kari, the awesome Ruby documentation browser!" },
{ title: "The egalitarian assumption..." },
{ title: "", _destroy: "1" } # this will be ignored
]
}}
member = Member.create(params['member'])
member.posts.length # => 2
member.posts.first.title # => 'Kari, the awesome Ruby documentation browser!'
member.posts.second.title # => 'The egalitarian assumption...'
You may also set a :reject_if proc to silently ignore any new record hashes if they fail to pass your criteria. For example, the previous example could be rewritten as:
class Member include Mongoid::Document has_many :posts accepts_nested_attributes_for \ :posts, reject_if: proc { |attributes| attributes["title"].blank? } end params = { member: { name: "joe", posts_attributes: [ { title: "Kari, the awesome Ruby documentation browser!" }, { title: "The egalitarian assumption of the modern citizen" }, { title: "" } # this will be ignored because of the :reject_if proc ] }} member = Member.create(params["member"]) member.posts.length # => 2 member.posts.first.title # => "Kari, the awesome Ruby documentation browser!" member.posts.second.title # => "The egalitarian assumption of the modern citizen"
Alternatively, :reject_if also accepts a symbol for using methods:
class Member include Mongoid::Document has_many :posts accepts_nested_attributes_for :posts, reject_if: :new_record? end class Member include Mongoid::Document has_many :posts accepts_nested_attributes_for :posts, reject_if: :reject_posts def reject_posts(attributed) attributed["title"].blank? end end
If the hash contains an id key that matches an already associated record, the matching record will be modified:
member.attributes = {
name: "Joe",
posts_attributes: [
{ id: 1, title: "[UPDATED] An, as of yet, undisclosed..." },
{ id: 2, title: "[UPDATED] other post" }
]
}
member.posts.first.title # => "[UPDATED] An, as of yet, undisclosed..."
member.posts.second.title # => "[UPDATED] other post"
By default the associated records are protected from being destroyed. If you want to destroy any of the associated records through the attributes hash , you have to enable it first using the :allow_destroy option. This will allow you to also use the _destroy key to destroy existing records:
class Member include Mongoid::Document has_many :posts accepts_nested_attributes_for :posts, allow_destroy: true end params = { member: { posts_attributes: [{ id: "2", _destroy: "1" }] }} member.attributes = params["member"] member.posts.detect { |p| p.id == 2 }.marked_for_destruction? # => true member.posts.length # => 2 member.save member.reload.posts.length # => 1
Many-to-Many
The behaviour is the same as in One-To-Many associations.
class Person include Mongoid::Document has_and_belongs_to_many :social_circles accepts_nested_attributes_for :social_circles end class SocialCircle include Mongoid::Document has_and_belongs_to_many :people end
Saving
All changes to models, including the destruction of those marked for destruction, are saved and destroyed automatically and atomically when the parent model is saved.