我有两个表,Teams
和Games
。我正在尝试为这些表设置关联,但遇到了一些问题。这是我的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_many
,home_team
和away_team
创建winning_team
吗?
答案 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