我有一个模型地址,如下面的
class Address
include Mongoid::Document
field :line1
field :city
# more fields like this
embedded_in :user, :inverse_of => :permanent_address
embedded_in :user, :inverse_of => :current_address
embedded_in :college, :inverse_of => :address
end
有大学和用户的模型嵌入地址
class College
include Mongoid::Document
references_many :users
embeds_one :address
# some fields and more code
end
class User
include Mongoid::Document
referenced_in :college, :inverse_of => :users
embeds_one :permanent_address, :class_name => "Address"
embeds_one :current_address, :class_name => "Address"
# fields and more code
end
我在上面的设置中遇到了一些问题。我使用单一表单来询问当前和永久地址以及更多信息,但只有current_address被保存,而且我在permanent_address中填充的数据也是如此。
Parameters:
{"utf8"=>"✓",
"authenticity_token"=>"KdOLvzmKyX341SSTc1SoUG6QIP9NplbAwkQkcx8cgdk=",
"user"=> {
"personal_info_attributes"=>{...},
"nick_names_attributes"=>{...},
"current_address_attributes"=>{
"line1"=>"",
"area"=>"",
"country"=>"USA",
"postal_code"=>"sd",
"city"=>"",
"state"=>"",
"landmark"=>"",
"id"=>"4d891397932ecf36a4000064"
},
"permanent_address_attributes"=>{
"line1"=>"",
"area"=>"asd",
"country"=>"india",
"postal_code"=>"",
"city"=>"",
"state"=>"",
"landmark"=>""
},
"commit"=>"Submit", "id"=>"4d8903d6932ecf32cf000001"}
MONGODB alma_connect['users'].find({:_id=>BSON::ObjectId('4d8903d6932ecf32cf000001')})
MONGODB alma_connect['users'].update({"_id"=>BSON::ObjectId('4d8903d6932ecf32cf000001')},
{"$set"=>{
"current_address"=>{
"line1"=>"",
"area"=>"asd",
"country"=>"india",
"postal_code"=>"",
"city"=>"",
"state"=>"",
"landmark"=>"",
"_id"=>BSON::ObjectId('4d8916e9932ecf381f000005')}}})
我不确定这是否是我在这里做错了还是有其他问题。我正在使用Rails 3.0.4和MongoID 2.0.0.rc.7
更新
我升级到mongoid 2.0.1并将我的用户更改为包含地址选项的反转。
class User
include Mongoid::Document
referenced_in :college, :inverse_of => :users
embeds_one :permanent_address, :class_name => "Address", :inverse_of => :permanent_address
embeds_one :current_address, :class_name => "Address", :inverse_of => :current_address
# fields and more code
end
我知道名称的反转没有意义,但这里的要点只是为了使它们不同,或者如果你的嵌入类中的关系有良好的名称(如:current_user,:permanent_user),你应该使用反转的。
答案 0 :(得分:2)
来自Mongoid docs
当子嵌入文档可以属于多种类型的父文档时,您可以通过在父项上的定义和子项上的多态选项中添加as选项来告诉Mongoid支持这一点。在子对象上,将存储一个指示父类型的附加字段。
class Band
include Mongoid::Document
embeds_many :photos, as: :photographic
has_one :address, as: :addressable
end
class Photo
include Mongoid::Document
embedded_in :photographic, polymorphic: true
end
class Address
include Mongoid::Document
belongs_to :addressable, polymorphic: true
end
答案 1 :(得分:1)
对我来说很好看。我有类似的设置,它按预期工作。