【发布时间】:2013-02-09 19:57:34
【问题描述】:
我有一个模型“Person”,它嵌入了多个“SuggestedPerson”。 SuggestedPerson 还引用另一个人(被建议的人)。所以 Person 需要 embed_many 和 has_many SuggestedPerson。问题是 Mongo 返回错误:
失败/错误: Mongoid::Errors::MixedRelations:
Problem: Referencing a(n) SuggestedPerson document from the Person document via a relational association is not allowed since theSuggestedPerson 已嵌入。
代码:
class Person
embeds_many :suggested_persons, :class_name => "SuggestedPerson", :inverse_of => :person
has_many :suggested_to_persons, :class_name => "SuggestedPerson", :inverse_of => :to_person
end
class SuggestedPerson
embedded_in :person, :class_name => "Person", :inverse_of => :suggested_persons
belongs_to :to_person, :class_name => "Person", :inverse_of => :suggested_to_persons
end
有没有办法解决这个问题?
【问题讨论】:
-
最快的方法是将关联更改为 has_many,但这是 hacky。
-
是的,谢谢,我就是这么做的:/
-
但我也想知道另一种解决方案不是破解...
-
没有任何其他解决方案...嵌入文档不能被嵌入它的模型以外的任何其他模型引用...因为documentation 说:
Documents that are embedded using the embeds_one macro are stored as a hash inside the parent in the parent's database collection.所以它们是没有单独存储...因此无法引用。
标签: ruby-on-rails mongodb mongoid