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,
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With