Foreign Key question

I’m a complete RoR newbie, and am working on a project involving games.
Each game involves two teams, and I’m trying to figure out how best to
set this up in the model.

Here is a snippet from my tables:

GAMES table:
game_id
home_team_id
away_team_id

TEAMS table:
team_id
name

Each game is represented by a single record in the Games table. Each
team is represented by a single record in the Teams table. Each game
has a home team and an away team.

The home_team_id and away_team_id fields both refer to the Teams table.
If there was only one team, the end product would be easy, but since I
have two different fields in the Game table that refer back to the same
validation table, I’m struggling.

Thanks in advance…

-Jeff Wigal

something Like this (no guarantee for correctness):

class Game < ActiveRecord::Base

belongs_to :hometeam, :foreign_key => :home_team_id, :class_name =>
“Team”
belongs_to :awayteam, :foreign_key => :away_team_id, :class_name =>
“Team”
end

class Game < ActiveRecord::Base

has_many :homegames, :foreign_key => :home_team_id, :class_name =>
“Game”
has_many :awaygames, :foreign_key => :away_team_id, :class_name =>
“Game”

end

Then you can do:

game = Game.find(1)
hometeam = game.hometeam
awayteam = game.awayteam
homegamesoffirstteam = hometeam.homegames

etc…

hope i did

Thanks! Should this…
Thorsten L wrote:

class Game < ActiveRecord::Base

has_many :homegames, :foreign_key => :home_team_id, :class_name =>
“Game”
has_many :awaygames, :foreign_key => :away_team_id, :class_name =>
“Game”

end

be this?

class Team < ActiveRecord::Base
has_many :homegames, :foreign_key => :home_team_id, :class_name
=>“Game”
has_many :awaygames, :foreign_key => :away_team_id, :class_name =>
“Game”
end

yeah sure, stupid me.

i copied the class header line from the first one as i’m lazy, and
forgot to change the class name :smiley: