Habtm or two foreign keys?

Somehow I keep running into this problem in different projects …

Say I want to represent soccer matches. A Match is associated with
exactly two Teams, and keeps the score each team achieved. I see two
choices:

a) add two foreign keys to Match and have it belong_to :team_a and
:team_b

pro: it is easy to match score_a to team_a and score_b to team_b, and it
is innately impossible to associate too many teams

con: I would need two rather ugly has_many associations in the Team
model, as in “has_many :team_a_matches / has_many :team_b_matches”
(right?)

b) use habtm

pro: nice and clean associations

con: associating score_a and score_b attributes in the Match model with
exactly the right team from Match#teams gets convoluted and error-prone,
and association validation is a bit more involved

How would you proceed? Am I missing a third option?

Thanks in advance,
Jan

I think you want this:

class Match < ActiveRecord::Base
belongs_to :team
end

class Team < ActiveRecord::Base
has_many :games, :foreign_key => :away_team
has_many :games, :foreign_key => :home_team
end

Then you can do
Team.find(1).games #displays home and away games
Game.find(1).home_team
Game.find(1).away_team

ESPNDev

Thanks for your input! I don’t really have the distinction into home and
away teams - I’m building a small app for the upcoming Euro Cup - but it
may be best to pretend I had and be done with it.

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs