8

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?

1 Answer 1

7

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.