has_many与同一个表的多个外键关联

时间:2016-02-10 22:23:33

标签: ruby-on-rails database

我有两个表,TeamsGames。我正在尝试为这些表设置关联,但遇到了一些问题。这是我的Game模型及其关联:

# Game Model

class Game < ActiveRecord::Base
  belongs_to :home_team, class_name: "Team"
  belongs_to :away_team, class_name: "Team"
  belongs_to :winning_team, class_name: "Team"
end

我可能会过度思考这个但我不确定如何设置我的Team模型来举办游戏。

在我的团队模型中使用简单的has_many :games,我的测试会返回以下错误:

Team Associations should have many games
     Failure/Error: it { should have_many(:games) }
       Expected Team to have a has_many association called games (Game does not have a team_id foreign key.)

我发现它正在为team_id寻找Game,因为它没有team_id错误。但在我的Game表中,我有三个外键引用同一个类。那么我需要为每个has_manyhome_teamaway_team创建winning_team吗?

1 个答案:

答案 0 :(得分:2)

你需要这样的东西:

class Team < ActiveRecord::Base
  has_many :home_games, class_name: 'Game', foreign_key: 'home_team_id'
  has_many :away_games, class_name: 'Game', foreign_key: 'away_team_id'

  # This seems like a separate thing to me...
  has_many :winning_games, class_name: 'Game', foreign_key: 'winning_team_id'

  # Do not include winning games, since it would already be included
  def games
    self.home_games.to_a + self.away_games.to_a
  end

end