我正在努力让以下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
答案 0 :(得分:4)
我不这么认为有一种直接的方法可以做到这一点,可能是你的解决方法
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 |
+--------------------------+-------+--------------------------+
abd你可以通过
得到总数>> Team.first.games
希望这有帮助