Sei*_*lam 7 ruby-on-rails mongodb mongoid
我正在尝试在Post模型中将viewer_ids保存为user_ids,并将User模型中的Viewed_ids保存到已查看的post_ids.当使用Rspec进行测试添加/删除并访问来自User的关系时,它很有用.但是当我使用RABL来查看post-while用户数据时,它会被混淆并给我一个不明确的关系.
#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
Run Code Online (Sandbox Code Playgroud)
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.
Run Code Online (Sandbox Code Playgroud)
那么问题是什么,我正在定义关系和它们的倒数.是否不可能在关系的反转中得到不同的数据?
问题是当在模型上具有相同类的多个关系时.因此,一旦添加了nn,每侧有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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1412 次 |
| 最近记录: |