# Bi-directional self-referential HABTM

**URL:** <https://www.ruby-forum.com/t/bi-directional-self-referential-habtm/110463>\
**Category:** Rails\
**Created:** [July 26, 2007, 4:37pm UTC](https://www.ruby-forum.com/t/bi-directional-self-referential-habtm/110463 "2007-07-26T16:37:50Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![jeroen](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/j/bbe5ce/32.png) [@jeroen](https://www.ruby-forum.com/u/jeroen)\
**Post date:** [July 26, 2007, 4:37pm UTC](https://www.ruby-forum.com/t/bi-directional-self-referential-habtm/110463/1 "2007-07-26T16:37:50Z")

</div>

Hi,

I’m having a little trouble figuring out how to make a self-  
referential HABTM bi-directional.

I have a Employee class. Each employee can have a couple of bosses,  
who are also employees. The employee class has the following HABTM:

has\_and\_belongs\_to\_many :bosses, :class\_name =\>  
“Employee”, :join\_table =\> “bosses\_courses”, :association\_foreign\_key  
=\> “boss\_id”, :foreign\_key =\> “employee\_id”

Now this works fine… but only one way. I can get all bosses of an  
employee but I can’t get all employees of a boss.

In hindsight I think it probaby would have been better to use  
a :through relationship for this, but I can’t really change the  
database schema now.

The solution might be to code something like a subordinate method for  
the employee class myself, but I’m not sure how to do that.

Does anyone has any good suggestions?

---

<div class="post-metadata">

**Author:** ![jeroen](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/j/bbe5ce/32.png) [@jeroen](https://www.ruby-forum.com/u/jeroen)\
**Post date:** [July 26, 2007, 6:42pm UTC](https://www.ruby-forum.com/t/bi-directional-self-referential-habtm/110463/2 "2007-07-26T18:42:02Z")

</div>

jeroen wrote:

> =\> “boss\_id”, :foreign\_key =\> “employee\_id”
> 
> Does anyone has any good suggestions?

You should just be able to add

has\_and\_belongs\_to\_many :employees, :class\_name =\> “Employee”,  
:join\_table =\> “bosses\_courses”, :association\_foreign\_key =\>  
“employee\_id”, :foreign\_key =\> “boss\_id”

Notice how I just changed the name of the relationship, and swapped the  
two keys. This should give you the “other” direction that you’re  
looking for. The :class\_name and :association\_foreign\_key arguments  
are probably not necessary in this one, but in this case I would keep  
them just to help clearly document the difference between the two  
relationships for myself months down the road.

–  
[http://www.5valleys.com/](http://www.5valleys.com/)
