Mongoid (Rails) 中的两个 1 - N 关系
场景是:
一个帐户如何给另一个帐户评分?这会导致帐户上出现两个列表。那些我评价过的人和那些评价过我的人。 (my_ ratings 和 ratings_given)
归结为:
与同一实体的多个 1 - N 关系如何在 Mongoid 中工作?
在 Mongoid 的文档中,它表示您可以使用 has_many
和 belongs_to
将实体链接在一起。
我目前在 Account 上有这个
has_many :ratings, :as => "my_ratings"
has_many :ratings, :as => "ratings_given"
,在 Ratings 上有这个:
belongs_to :user, :as => 'Rater'
belongs_to :user, :as => 'Ratie'
文档不涵盖这种情况,所以我认为你必须使用 :as 参数来区分两者。
这甚至是远程正确的吗?
The scenario is:
How can an Account give ratings to another account? This results in two lists on the Account. Those who I have rated and those who have rated me. (my_ratings and ratings_given)
This boils down to:
How can multiple 1 - N relationsips to the same entity work in Mongoid?
In Mongoid's Docs it says you can use has_many
and belongs_to
to link the entities together.
I currently have this on Account
has_many :ratings, :as => "my_ratings"
has_many :ratings, :as => "ratings_given"
and this on Ratings:
belongs_to :user, :as => 'Rater'
belongs_to :user, :as => 'Ratie'
The docs don't cover this case, so I thought you would have to differentiate between the two with an :as parameter.
Is this even remoting correct?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以使用 class_name 和 inverse_of 选项来实现您想要的目的:
自从我上次使用它以来,文档已经发生了变化,所以我不确定这是否仍然是推荐的方法。看起来它没有在 1-many 引用页面。但是,如果您查看关系的一般页面,它们就会被涵盖那里。
在任何情况下,当同一个类有两个关联时,您需要显式链接 ratings_given/rater 和 my_ ratings/ratee 关联,否则 mongoid 无法知道选择两个潜在逆中的哪一个。
You can achieve what you want using the class_name and inverse_of options:
The documentation has changed since I was last working with it so I wasn't sure whether this is still the recommended approach. Looks like it doesn't mention these options on the 1-many referenced page. But if you take a look at the general page on relations they are covered there.
In any case you need to explicitly link ratings_given/rater and my_ratings/ratee associations when there are two associations to the same class, otherwise mongoid has no way to know which of the two potential inverses to pick.