0

我在更新 mongodb 中的嵌入文档时遇到问题。
我有以下情况。用户模型具有作为嵌入式文档的地址。
我能够将地址嵌入到父模型中,即;用户模型,但我仍然无法弄清楚如何更新嵌入的地址,即使我嵌入了地址的 _id

请帮忙
谢谢

4

2 回答 2

2

您必须从父级检索嵌入文档,然后进行更新操作,例如:

address = user.address
address.update_attributes(:street => "foo")
于 2010-07-27T17:11:19.090 回答
1

还有另一种解决方案。如果 Person 和 Preference 类之间存在多对多关系,则:

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"

于 2010-11-05T00:51:33.527 回答