问题描述
场景为:
一个帐户如何给另一个帐户评分?这将在帐户上显示两个列表.那些我评价过的人和那些评价过我的人. (my_ratings和ratings_given)
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)
这可以归结为:
在Mongoid中如何对同一个实体使用多个1-N个关联?
How can multiple 1 - N relationsips to the same entity work in Mongoid?
在Mongoid的文档中,您可以使用has_many
和belongs_to
将实体链接在一起.
In Mongoid's Docs it says you can use has_many
and belongs_to
to link the entities together.
我目前在帐户
has_many :ratings, :as => "my_ratings"
has_many :ratings, :as => "ratings_given"
,并在评分上显示:
belongs_to :user, :as => 'Rater'
belongs_to :user, :as => 'Ratie'
文档没有涵盖这种情况,所以我认为您必须使用:as参数来区分两者.
The docs don't cover this case, so I thought you would have to differentiate between the two with an :as parameter.
这甚至是正确的吗?
推荐答案
您可以使用class_name和inverse_of选项实现所需的目标:
You can achieve what you want using the class_name and inverse_of options:
class Account
include Mongoid::Document
field :name
has_many :ratings_given, :class_name => 'Ratings', :inverse_of => :rater
has_many :my_ratings, :class_name => 'Ratings', :inverse_of => :ratee
end
class Ratings
include Mongoid::Document
field :name
belongs_to :rater, :class_name => 'Account', :inverse_of => :ratings_given
belongs_to :ratee, :class_name => 'Account', :inverse_of => :my_ratings
end
自从我上一次使用文档以来,文档已经发生了更改,因此我不确定这是否仍然是推荐的方法.看起来在 1-许多引用页面.但是,如果您查看关系上的常规页面在那里.
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.
在任何情况下,当有两个关联属于同一类时,您都需要显式链接rating_given/rater和my_ratings/ratee关联,否则mongoid无法知道要选择的两个潜在逆中的哪一个.
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.
这篇关于Mongoid中的两个1-N关系(Rails)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!