CamelCamelCamel
CamelCamelCamel

Reputation: 5200

Mongoid - Updating Nested Attributes

From the mongoid docs:

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...'

Is there a way to update nested attributes instead of creating them?

Upvotes: 0

Views: 1538

Answers (1)

Ron
Ron

Reputation: 1166

It relies on the nested documents having IDs.

In a Rails form, for instance, the corresponding attributes fields (in your case, posts_attributes) will be passed as part of the form. Rails then does an update for elements with an ID, and a create for those without an ID.

Upvotes: 1

Related Questions