ActiveRecord有两个关联

时间:2010-11-28 19:09:06

标签: ruby-on-rails ruby activerecord

实现与activerecord有两个关联的最佳方法是什么?

我有团队和游戏模型。每个团队都会有很多游戏@team.games。游戏将有两个团队@game.hosting_team@game.opposing_team

我开始时有两个belongs_to/has_one个关联,但@team.games只会返回他们的主场比赛。

我能想到的另一个选择是使用HABTM并使用验证器来确保只有记录。唯一缺少的就是跟踪主队。似乎我需要一个有很多通过关联,但我不完全确定...

感谢您的帮助。

这是两个has_many关联的外观示例。这里的问题是我必须致电team.gamesteam.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

1 个答案:

答案 0 :(得分:3)

您仍然可以使用bt / ho关联对其进行建模,并将游戏设置为团队中的访问者方法,而不是作为关联:

class Team < ActiveRecord::Base
  def games
    Game.find(:conditions => ["home_team_id = ? OR away_team_id = ?", id, id])
  end
end