field :parent_topic_id, type: Integer, default: -1
has_many :topics, :dependent => :destroy
belongs_to :parent_topic, :class_name => 'Topic', :foreign_key => :parent_topic_id
belongs_to :talk_group
上面的关系适用于sqlite / mysql,但不适用于mongoid 因为当一个模型不能有多个而且belongs_to与另一个相同的模型
时parent_topic.talk_group将出现Mongoid :: Errors :: AmbiguousRelationship:error
答案 0 :(得分:0)
问题的产生不是因为“当一个模型不能有多个而且belongs_to与另一个相同的模型”时。
这是因为当mongoid查看topic
模型时,它无法知道talk_group
字段是否指的是topics
或parent_topic
关系talk_group
1}}模型。
mongoid提供了一个选项来避免这种“AmbiguousRelationship”它是inverse_of
选项......
因此,要解决此问题,您应该将topic
模型更改为
belongs_to :talk_group, inverse_of: :parent_topic
并且talk_group模型应该变为
has_many :topics, dependent: :destroy
belongs_to :parent_topic, class_name: 'Topic'
# you can add inverse_of option on this side as well although it's not mandatory
belongs_to :parent_topic, class_name: 'Topic', inverse_of: :talk_group
还可以参考this question获取更多信息。