Question

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

That seemed like just too much work for what i wanted to achieve.

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

Was it helpful?

Solution

Your solution is fine as the same event belongs to two teams. The polymorphic associations are applicable when several models are eventable.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top