# HABTM relationship between 2 of the same class

**URL:** <https://www.ruby-forum.com/t/habtm-relationship-between-2-of-the-same-class/141320>\
**Category:** Rails\
**Created:** [June 24, 2008, 6:06pm UTC](https://www.ruby-forum.com/t/habtm-relationship-between-2-of-the-same-class/141320 "2008-06-24T18:06:47Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![Iain\_A](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/i/6bbea6/32.png) [@Iain\_A](https://www.ruby-forum.com/u/Iain_A)\
**Post date:** [June 24, 2008, 6:06pm UTC](https://www.ruby-forum.com/t/habtm-relationship-between-2-of-the-same-class/141320/1 "2008-06-24T18:06:47Z")

</div>

Hello.

I am trying to figure out the neatest way to do this. So far I have a  
class called Member. Now I am trying to organise the relationship  
“Alliance”.

This relationship means that 2 Members can become allies and they have  
an alliance together. My problem comes when trying to create a) the  
table b) the relationships.

I have ended up with the following. But was wondering if anyone could  
think of a more elegant way of doing this.

class Member \< ActiveRecord::Base

has\_many :init\_alliances, :foreign\_key =\> ‘initiator\_id’, :class\_name  
=\> ‘Alliance’  
has\_many :accept\_alliances, :foreign\_key =\> ‘acceptor\_id’, :class\_name  
=\> ‘Alliance’

def allies  
return (self.accept\_alliances.collect{|a|a.initiator} +  
self.init\_alliances.collect{|a| a.acceptor}).uniq  
end

end

class Alliance \< ActiveRecord::Base  
belongs\_to :initiator, :foreign\_key =\> ‘initiator\_id’, :class\_name  
=\> ‘Member’  
belongs\_to :acceptor, :foreign\_key =\> ‘acceptor\_id’, :class\_name  
=\> ‘Member’  
end

**Alliance Table**

id | initiator\_id | acceptor\_id

---

<div class="post-metadata">

**Author:** ![Iain\_A](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/i/6bbea6/32.png) [@Iain\_A](https://www.ruby-forum.com/u/Iain_A)\
**Post date:** [June 24, 2008, 6:17pm UTC](https://www.ruby-forum.com/t/habtm-relationship-between-2-of-the-same-class/141320/2 "2008-06-24T18:17:19Z")

</div>

> **[The real John Ford](https://johnford.is/)**
>
> I’m doing the things I love.

That link goes over the “has many through” example. That’s what you  
are trying to do. Takes a bit to get used to what’s going on.  
Basically you have a friendship model (or alliance in your case) with  
a user\_id and a friend\_id, the friendship model belongs to user and  
belongs to friend, :class\_name =\> user. In the user model, a user has  
many friendships (or alliances) and has many friends through  
alliances.

See the example, and ask more questions if it doesn’t work just right.
