我有两个班,即Person
和Language
。每个语言都有创建者和更新者,他们都来自Person
类。我想通过子节点查询父节点的属性,反之亦然。
人类
class Person
include Mongoid::Document
field :first_name, type: String
field :last_name, type: String
has_many :created_languages, class_name: 'Language', inverse_of: :created_by, foreign_key: 'created_by_id', autosave: true
accepts_nested_attributes_for :created_languages
has_many :updated_languages, class_name: 'Language', inverse_of: :updated_by, foreign_key: 'updated_by_id', autosave: true
accepts_nested_attributes_for :updated_languages
end
语言课
class Language
include Mongoid::Document
field :content, type: String
belongs_to :created_by, class_name: 'Person', inverse_of: :created_languages, foreign_key: :created_by_id, autosave: true
accepts_nested_attributes_for :created_by
belongs_to :updated_by, class_name: 'Person', inverse_of: :updated_languages, foreign_key: :updated_by_id, autosave: true
accepts_nested_attributes_for :updated_by
end
我想在Rails应用程序中查询的内容如下:即在Rails控制台中:
ruby 2.0.0p451 > a = Person.create!(first_name: "Marco", last_name:"Reus")
ruby 2.0.0p451 > b = Language.create!(content: "German", created_by_id: a.id, updated_by_id: a.id)
ruby 2.0.0p451 > a.created_languages (now works)
ruby 2.0.0p451 > a.updated_languages (now works)
ruby 2.0.0p451 > b.created_by (now works)
ruby 2.0.0p451 > b.updated_by (now works)
我以前收到以下错误。通过上面的代码,它就解决了。
Mongoid ::错误:: AmbiguousRelationship:
问题:模糊关系:created_languages,:在Person上定义的updated_languages。
摘要:当Mongoid尝试在内存中设置关系的逆文档时,需要知道它属于哪个关系。设置:updated_by时,Mongoid在类Language上查找匹配关系,但是找到了可能匹配的倍数:: created_languages,:updated_languages。
解决方案:在关于语言的:updated_by关系中,您必须添加:inverse_of选项以指定Person上的确切关系:updated_by。
答案 0 :(得分:0)
您还应该为所有这些包含inverse_of:
has_many :created_languages, class_name: 'Language', :inverse_of => :created_by
belongs_to :created_by, class_name: 'Person', :inverse_of => :created_languages
希望它有所帮助。