Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ambiguous Relationship in Mongoid

I'm trying to have viewer_ids in a Post model to save user_ids, and viewed_ids in User model to post_ids that got viewed. The thing when testing using Rspec to add/delete and access the relation from User it works great. But when I use RABL to view the post —while user data is embedded— it gets confused and give me the Ambiguous Relationship.

#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.

So what is the problem, i'm defining both relations and the inverse of them. Is it not possible to have different data in inverse of a relation?

like image 994
Seif Sallam Avatar asked Mar 23 '13 09:03

Seif Sallam


1 Answers

The problem was when having multiple relations of the same class on a model. So once the n-n was added there was 2 user relations and 2 post relations on each side.

#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

Thanks to Duran for his clearing this up https://jira.mongodb.org/browse/MONGOID-2923?focusedCommentId=982950&page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel#comment-982950

like image 129
Seif Sallam Avatar answered Nov 15 '22 19:11

Seif Sallam