实现与ActiveRecord有两种关联的最佳方法是什么?
我有一个团队和游戏模型。每队有许多场比赛
@team.games
. 一场比赛有两个队
@game.hosting_team
和
@game.opposing_team
.
我从两个开始
belongs_to/has_one
但之后
团队游戏
只会返回他们的主场比赛。
我能想到的另一个选择是使用habtm并使用验证器来确保只有记录。唯一缺少的就是跟踪主队。似乎我需要一个有很多通过协会,但我不完全确定…
谢谢你的帮助。
这是两个有很多关联的例子。问题是我得打电话
team.games
和
team.opponents
获取他们游戏的完整列表
class Team < ActiveRecord::Base
has_many :games
has_many :opponents, :class_name => "Team"#, :foreign_key => ""
end
class Game < ActiveRecord::Base
belongs_to :team, :class_name => "Team" #, :foreign_key => "team_id"
belongs_to :opponent, :class_name => "Team" #, :foreign_key => "opponent_id"
end
我想要这样的东西,但这显然不是你的工作方式。
class Team < ActiveRecord::Base
has_many :games
end
class Game < ActiveRecord::Base
belongs_to :hosting_team
belongs_to :opposing_team
end
我想要的API看起来像这样。
@team.games # return all games home or away
@game.hosting_team # Team
@game.opposing_team # Team