开发者

update embedded documents mongodb with mongoid

开发者 https://www.devze.com 2023-01-09 15:11 出处:网络
I am having problem updating the embedded documents开发者_如何学Go in mongodb. I have a following scenario.

I am having problem updating the embedded documents开发者_如何学Go in mongodb.

I have a following scenario. A User model has address as the embedded docs.

I am able to embed the address to the parent model ie; User model but i still cant figure out how to update the address embedded even though i have the _id of the address embedded

Please help

Thanks


You have to retrieve the embedded document from the parent and then make the update operation, e.g:

address = user.address
address.update_attributes(:street => "foo")


There's another solution. If there's a many-to-many relationship between the Person and Preference classes, then:

ruby-1.9.2-p0 > Person.count
 => 0
ruby-1.9.2-p0 > Preference.count
 => 0
ruby-1.9.2-p0 > person = Person.create
 => #< Person _id: 4cd353e92b58af214b000006, preference_ids: []>
ruby-1.9.2-p0 > pref = Preference.create
 => #< Preference _id: 4cd353ee2b58af214b000007, person_ids: [], name: nil>
ruby-1.9.2-p0 > 
ruby-1.9.2-p0 > person.preferences << pref
 => true
ruby-1.9.2-p0 > Preference.first.people.count
 => 1
ruby-1.9.2-p0 > Person.first.preferences.count
 => 1
ruby-1.9.2-p0 > 
ruby-1.9.2-p0 > person.preferences.first.name = 'foobar'
 => "foobar"
ruby-1.9.2-p0 > person.preferences.first.save
 => true
ruby-1.9.2-p0 > pref.reload
 => #< Preference _id: 4cd353ee2b58af214b000007, person_ids: [BSON::ObjectId('4cd353e92b58af214b000006')], name: "foobar">
ruby-1.9.2-p0 > pref.name
 => "foobar"

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号