Mongoid – 同一外域的两个场反转

我正试图让以下Mongoid关系起作用,但每个团队的游戏领域都是一个空数组。 这不是一个有效的关系模型吗? 我是否需要拆分游戏,即home_games和away_games?

class Team include Mongoid::Document has_many :games, :autosave => true end class Game include Mongoid::Document belongs_to :home_team, :class_name => "Team", :inverse_of => :games belongs_to :away_team, :class_name => "Team", :inverse_of => :games end 

我不这么认为有一个直接的方法来做到这一点,可能是你解决方法

 class Team include Mongoid::Document has_many :home_played, :class_name => 'Game' , :inverse_of => :home_team has_many :away_played, :class_name => 'Game' , :inverse_of => :away_team def games Game.any_of({:home_team_id => self.id},{:away_team_id => self.id}) end end class Game include Mongoid::Document belongs_to :home_team, :class_name => "Team", :inverse_of => :home_played belongs_to :away_team, :class_name => "Team", :inverse_of => :away_played end 

所以现在你可以像使用它一样

 g = Game.new +--------------------------+-------+--------------------------+--------------+--------------+ | _id | _type | _id | home_team_id | away_team_id | +--------------------------+-------+--------------------------+--------------+--------------+ | 4ec76f70b356f8031f000001 | | 4ec76f70b356f8031f000001 | | | +--------------------------+-------+--------------------------+--------------+--------------+ 1 row in set >> t=Team.new +--------------------------+-------+--------------------------+ | _id | _type | _id | +--------------------------+-------+--------------------------+ | 4ec76f75b356f8031f000002 | | 4ec76f75b356f8031f000002 | +--------------------------+-------+--------------------------+ 1 row in set >> t.save => true g.home_team = t +--------------------------+-------+--------------------------+ | _id | _type | _id | +--------------------------+-------+--------------------------+ | 4ec76f75b356f8031f000002 | | 4ec76f75b356f8031f000002 | +--------------------------+-------+--------------------------+ 1 row in set >> g.save => true 

 >> Team.first.home_played +--------------------------+-------+--------------------------+--------------------------+--------------+ | _id | _type | _id | home_team_id | away_team_id | +--------------------------+-------+--------------------------+--------------------------+--------------+ | 4ec76f70b356f8031f000001 | | 4ec76f70b356f8031f000001 | 4ec76f75b356f8031f000002 | | +--------------------------+-------+--------------------------+--------------------------+--------------+ 1 row in set >> Game.first.home_team +--------------------------+-------+--------------------------+ | _id | _type | _id | +--------------------------+-------+--------------------------+ | 4ec76f75b356f8031f000002 | | 4ec76f75b356f8031f000002 | +--------------------------+-------+--------------------------+ 

你可以得到总数

 >> Team.first.games 

希望这可以帮助