Active Record two belongs_to calls or single table inheritance

Posted by ethyreal on Stack Overflow See other posts from Stack Overflow or by ethyreal
Published on 2010-03-27T19:51:56Z Indexed on 2010/03/27 21:33 UTC
Read the original article Hit count: 391

In linking a sports event to two teams, at first this seemed to make sense:

events
  - id:integer
  - integer:home_team_id
  - integer:away_team_id

teams
  - integer:id
  - string:name

However I am troubled by how I would link that up in the active record model:

class Event
  belongs_to :home_team, :class_name => 'Team', :foreign_key => "home_team_id"
  belongs_to :away_team, :class_name => 'Team', :foreign_key => "away_team_id"
end

Is that the best solution?

In an answer to a similar question I was pointed to single table inheritance, and then later found polymorphic associations. Neither of which seemed to fit this association. Perhaps I am looking at this wrong, but I see no need to subclass a team into home and away teams since the distinction is only in where the game is played. If I did go with single table inheritance I wouldn't want each team to belong_to an event so would this work?

# app/models/event.rb
class Event < ActiveRecord::Base
  belongs_to :home_team
  belongs_to :away_team
end

# app/models/team.rb
class Team < ActiveRecord::Base
  has_many :teams
end

# app/models/home_team.rb
class HomeTeam < Team

end

# app/models/away_team.rb
class AwayTeam < Team

end

I thought also about a has_many through association but that seems two much as I will only ever need two teams, but those two teams don't belong to any one event.

event_teams
  - integer:event_id
  - integer:team_id
  - boolean:is_home

Is there a cleaner more semantic way for making these associations in active record? or is one of these solutions the best choice?

Thanks

© Stack Overflow or respective owner

Related posts about activerecord

Related posts about ruby-on-rails