Active Record two belongs_to calls to the same model

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 20:33 UTC
Read the original article Hit count: 315

Filed under:
|

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

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.

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?

Thanks

© Stack Overflow or respective owner

Related posts about activerecord

Related posts about ruby-on-rails