# Habtm or two foreign keys?

**URL:** <https://www.ruby-forum.com/t/habtm-or-two-foreign-keys/136421>\
**Category:** Rails\
**Created:** [May 1, 2008, 10:50pm UTC](https://www.ruby-forum.com/t/habtm-or-two-foreign-keys/136421 "2008-05-01T22:50:45Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![janfoeh](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/j/8baadc/32.png) [@janfoeh](https://www.ruby-forum.com/u/janfoeh)\
**Post date:** [May 1, 2008, 10:50pm UTC](https://www.ruby-forum.com/t/habtm-or-two-foreign-keys/136421/1 "2008-05-01T22:50:45Z")

</div>

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

---

<div class="post-metadata">

**Author:** ![janfoeh](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/j/8baadc/32.png) [@janfoeh](https://www.ruby-forum.com/u/janfoeh)\
**Post date:** [May 2, 2008, 1:27am UTC](https://www.ruby-forum.com/t/habtm-or-two-foreign-keys/136421/2 "2008-05-02T01:27:19Z")

</div>

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

---

<div class="post-metadata">

**Author:** ![janfoeh](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/j/8baadc/32.png) [@janfoeh](https://www.ruby-forum.com/u/janfoeh)\
**Post date:** [May 2, 2008, 8:23am UTC](https://www.ruby-forum.com/t/habtm-or-two-foreign-keys/136421/3 "2008-05-02T08:23:10Z")

</div>

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.
