mikeymurph77
mikeymurph77

Reputation: 802

has_many association with multiple foreign keys to the same table

I have two tables, Teams and Games. I am trying to set up the associations for these tables but running into some issues. Here is my Game model with it's associations:

# 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

I may be overthinking this but I'm not sure how to set up my Team model to have_many Games.

With a simple has_many :games in my Team model, my tests return the following error:

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.)

I see that it's looking for team_id for Game, and since there's no team_id it errors. But in my Game table I have three foreign keys referencing the same class. So would I need to create a has_many for each home_team, away_team and winning_team?

Upvotes: 1

Views: 870

Answers (1)

GoGoCarl
GoGoCarl

Reputation: 2519

You'll need something like:

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

Upvotes: 2

Related Questions