Mongoid ::错误:: AmbiguousRelationship:

时间:2014-12-08 03:54:55

标签: ruby-on-rails mongoid entity-relationship

talk_groups表

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

1 个答案:

答案 0 :(得分:0)

问题的产生不是因为“当一个模型不能有多个而且belongs_to与另一个相同的模型”时。

这是因为当mongoid查看topic模型时,它无法知道talk_group字段是否指的是topicsparent_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获取更多信息。