2016-02-10 61 views
1

我有两个表,TeamsGames。我正在尝试为这些表设置关联,但遇到一些问题。这是我的Game模型与它的关联:has_many与多个外键关联到同一个表

# 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模型have_many游戏。

在我的团队模型的简单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_idGame,并且因为没有team_id它的错误。但在我的Game表中,我有三个外键引用同一个类。那么我需要为每个home_teamaway_teamwinning_team创建一个has_many

+0

有关数据库设计的一个问题不应该包括在它的ORM或应用软件。这不是数据库设计的正确工具。 EVER!真正的数据库设计将有三张表格,包括关于游戏细节的游戏,关于团队细节的团队和团队合作伙伴关系作为多对多关联的联结表。 – HLGEM

+0

@HLGEM这似乎不是一个关于数据库设计的问题,数据库已经以功能方式设置。问题是你可以用一个has_many参考或不参与所有三个关联。另外,为什么你建议一个连接表?在这种情况下,关于比赛的细节是两个球队的比赛,看起来像一个连接表将是矫枉过正。也许我错过了什么?我认为数据库设计是正确的。 – GoGoCarl

+0

@GoGoCarl谢谢,我开始怀疑我的方法。是的,我正在寻找一种方法来处理has_many与单行,或作为三个单独的has_many行。 – mikeymurph77

回答

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 
+0

谢谢,这完美的作品,让我的测试通过。非常感激。 – mikeymurph77