5
实现一个与activerecord有两个关联的最佳方式是什么?ActiveRecord有两个关联
我有团队和游戏模型。每个团队将有多种游戏@team.games
。一场比赛将有两支球队@game.hosting_team
和@game.opposing_team
。
我开始与两个belongs_to/has_one
协会,但然后@team.games
只会返回他们的主场比赛。
我能想到的另一个选择是使用HABTM并使用验证器来确保只有记录。唯一缺少的是跟踪主队。似乎我需要一个有很多通过关联,但我不完全确定...
感谢您的帮助。
这是两个has_many关联的外观示例。这里的问题是我得打个电话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
的完整列表,我想这样的事情,但是这显然并不怎么belongs_to的作品。
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
你能calrify模型的关系,也许发布你的db/schema.rb? – 2010-11-28 19:48:44
谢谢。我编辑了这个问题。 – jspooner 2010-11-28 20:13:36