【问题标题】:Ambiguous Relationship in MongoidMongoid中的模糊关系
【发布时间】:2013-03-23 09:11:14
【问题描述】:

我试图在 Post 模型中使用 viewer_ids 来保存 user_ids,并在 User 模型中使用 viewer_ids 来保存被查看的 post_ids。使用 Rspec 进行测试以添加/删除和访问来自用户的关系时,它工作得很好。但是当我使用 RABL 来查看帖子时——同时嵌入了用户数据——它会变得很困惑,并给我一个模糊的关系。

#Post class
belongs_to :user
has_and_belongs_to_many :viewers, class_name: 'User', inverse_of: :viewed  

#User class
has_many :users
has_and_belongs_to_many :viewed, class_name: 'Post', inverse_of: :viewers

Mongoid::Errors::AmbiguousRelationship in Posts#show

Problem:
Ambiguous relations :posts, :viewed defined on User.
Summary:
When Mongoid attempts to set an inverse document of a relation in memory, it needs to know which relation it belongs to. When setting :user, Mongoid looked on the class Post for a matching relation, but multiples were found that could potentially match: :posts, :viewed.
Resolution:
On the :user relation on Post you must add an :inverse_of option to specify the exact relationship on User that is the opposite of :user.

那么问题是什么,我同时定义了关系和它们的倒数。是否不可能有不同的数据与关系相反?

【问题讨论】:

    标签: ruby-on-rails mongodb mongoid


    【解决方案1】:

    问题是在模型上具有同一类的多个关系时。因此,一旦添加了 n-n,每边就有 2 个用户关系和 2 个帖子关系。

    #Post class
    belongs_to :user, inverse_of: :posts
    has_and_belongs_to_many :viewers, class_name: 'User', inverse_of: :viewed  
    
    #User class
    has_many :posts, inverse_of: :user
    has_and_belongs_to_many :viewed, class_name: 'Post', inverse_of: :viewers
    

    感谢杜兰https://jira.mongodb.org/browse/MONGOID-2923?focusedCommentId=982950&page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel#comment-982950

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-08-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多