has_many
will look for a foreign key with the same name as the class you're working in.
In this case, Rails will assume there is a team_id
in the associated Game
class, linking back to the Team.This isn't the case, so you need to be more explicit.
In this case, you also don't have a single link from a Game back to a Team. There are two different links between Game and Team, so you need to represent both of these links as associations:
class Team < ActiveRecord::Base
has_many :home_games, class_name: 'Game', foreign_key: :home_team_id
has_many :visitor_games, class_name: 'Game', foreign_key: :visitor_team_id
end
If you want to get all games for a given team, regardless of whether they are home or visitng games, you can define a method:
class Team < ActiveRecord::Base
has_many :home_games, class_name: 'Game', foreign_key: :home_team_id
has_many :visitor_games, class_name: 'Game', foreign_key: :visitor_team_id
def games
Game.where('home_team_id = ? or visitor_team_id = ?', id, id)
end
end