0
votes

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?

1
can you post your schema, it should be simpler to answer. - Andrew Orsich
It's a really large schema, I'll cut it down and post it. - CamelCamelCamel
Any chance you could post the schema or did you get this solved myxospsm? - Tyler Brock
I did not solve this yet. I don't have a schema, I was just curious. Say I have a post and comments, how do I update the comments from the post and not just create them? - CamelCamelCamel

1 Answers

1
votes

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.