0

I am having problem updating the embedded documents 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

starblue
  • 55,348
  • 14
  • 97
  • 151
Gagan
  • 4,278
  • 7
  • 46
  • 71

2 Answers2

2

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")
jpemberthy
  • 7,473
  • 8
  • 44
  • 52
  • thanks for reply jpemberthy, but this is still not working for me. I can clearly see in my development log like this project_name_development['people'].update({"_id"=>BSON::ObjectID('4c5106b6f1936f036c000008'), "address._id"=>"4c5106b6f1936f036c000006"}, {"$set"=>{"address.city"=>"bhaktapur", "address.province"=>"kathmandu"}}) which i think should update the address. And i have "address.update_attributes(address_attribute)" in my Person model where address_attribute is the hash of address Am i missing something? – Gagan Jul 29 '10 at 04:45
  • I'm not sure what could be happening then, If you want, please paste a console flow and the models code in a gist, so It will be easier to help you. – jpemberthy Jul 29 '10 at 14:10
  • thanks for replying. i figured out that there is error in my model so its not updating. thanks again – Gagan Aug 02 '10 at 07:21
1

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"
nickh
  • 4,721
  • 2
  • 29
  • 31