views:

25

answers:

1

I'm designing a basic sports application in RoR and I don't know if my database design is correct. For instance, I have:

class Game < ActiveRecord::Base
  has_one :home_team
  has_one :away_team
end

class Team < ActiveRecord::Base
  has_many :games
end

However, someone told me the better way to do this is:

class Game < ActiveRecord::Base
  has_many :teams, :through => :game_teams, :limit => 2
end

class Team < ActiveRecord::Base
  has_many :games, :through => :game_teams
end

class Game_Teams < ActiveRecord::Base
  belongs_to :game
  belongs_to :team
end

Is there a reason I would or wouldn't want either design?

+1  A: 

I don't think your first approach will work as it stands. If your games table has two fields home_team_id and away_team_id then your has_one associations will have to be something like has_one :home_team, :class => 'Team'

Also, Team has_many :games will assume that the game table has a field team_id so you will need to add :conditions or maybe :finder_sql to get Team to look in both home_team_id and away_team_id to find its games. This illustrates the downside of your first approach, essentially whenever you want to know all the games for a team you have 2 fields to look at.

mikej