# HABTM using two columns

**URL:** <https://www.ruby-forum.com/t/habtm-using-two-columns/138747>\
**Category:** Rails\
**Created:** [May 27, 2008, 1:09pm UTC](https://www.ruby-forum.com/t/habtm-using-two-columns/138747 "2008-05-27T13:09:18Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![meisterflexer](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/m/5f8ce5/32.png) [@meisterflexer](https://www.ruby-forum.com/u/meisterflexer)\
**Post date:** [May 27, 2008, 1:09pm UTC](https://www.ruby-forum.com/t/habtm-using-two-columns/138747/1 "2008-05-27T13:09:18Z")

</div>

Hi all,

I was wondering whether anyone could guide me to docu and code  
examples how to create and use a has\_and\_belongs\_to\_many relationship  
with a joining table where TWO columns are used to identify the  
relation to TWO alternative tables.

Example:  
table 1: mothers [mother\_id, name]  
table 2: fathers [father\_id, name]  
table 3: children [child\_id, name]  
joining table 4: children\_parent [child\_id, parent\_id, parent\_type]

‘parent type’ can be either ‘mother’ or ‘father’, and depending on  
this, the ‘parent\_id’ links to an entry in either the father or mother  
table.  
How do you define this in Rails and how do you query it when showing  
the child data?

Thanks for any suggestions,  
Flexer.

---

<div class="post-metadata">

**Author:** ![meisterflexer](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/m/5f8ce5/32.png) [@meisterflexer](https://www.ruby-forum.com/u/meisterflexer)\
**Post date:** [May 27, 2008, 3:19pm UTC](https://www.ruby-forum.com/t/habtm-using-two-columns/138747/2 "2008-05-27T15:19:46Z")

</div>

Before you get too far, I’d reconsider the models you’re using…

Mothers, Fathers, and Children are all people, and ideally a Person is  
in your database just once (the person who is a child can also be a  
father, etc).

What makes a Person a Mother, or Father (or grandmother, grandfather,  
etc) is just a relationship between that Person and another.

Factor the relationships out into something like:

Relation  
person\_1  
relation\_type  
person\_2  
where “person\_1” is the “relation\_type” of “person\_2”

and you can start supporting Mother, Father, Sister, Brother, Friend,  
Enemy, etc, etc.

---

<div class="post-metadata">

**Author:** ![meisterflexer](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/m/5f8ce5/32.png) [@meisterflexer](https://www.ruby-forum.com/u/meisterflexer)\
**Post date:** [May 27, 2008, 3:22pm UTC](https://www.ruby-forum.com/t/habtm-using-two-columns/138747/3 "2008-05-27T15:22:22Z")

</div>

Sounds like you want Polymorphic Associations: see  
[http://wiki.rubyonrails.org/rails/pages/HowToUsePolymorphicAssociations](http://wiki.rubyonrails.org/rails/pages/HowToUsePolymorphicAssociations)

On May 27, 6:05 am, meisterflexer [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid)
