Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails Associations - Multiple has_one relationships to the same class

An example of my issue is a sports game. A sports game has two teams, a home team and an away team. My active record models are as follows:

class Team < ActiveRecord::Base

  belongs_to :game

end

class Game < ActiveRecord::Base

  has_one :home_team, :class_name => "Team"
  has_one :away_team, :class_name => "Team"

end

I want to be able to access a team through the game, for example: Game.find(1).home_team

But I am getting an unitialized constant error: Game::team. Can anyone tell me what I'm doing wrong? Thanks,

like image 944
Ryan Fuentes Avatar asked Jan 27 '12 17:01

Ryan Fuentes


1 Answers

If Game has_one :team then Rails assumes your teams table has a game_id column. What you want though is for the games table to have a team_id column, in which case you'd use Game belongs_to :team. As English it does sound backwards in this case, but as Ruby, it's correct.

I did simplify a little. You'd want 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'
end

class Game < ActiveRecord::Base
  belongs_to :home_team, :class_name => "Team"
  belongs_to :away_team, :class_name => "Team"
end
like image 69
tybro0103 Avatar answered Oct 11 '22 22:10

tybro0103