# Table that have many-to-may relationship to itself

**URL:** <https://www.ruby-forum.com/t/table-that-have-many-to-may-relationship-to-itself/58290>\
**Category:** Rails\
**Created:** [April 20, 2006, 9:52am UTC](https://www.ruby-forum.com/t/table-that-have-many-to-may-relationship-to-itself/58290 "2006-04-20T09:52:49Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![lgao](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/l/e68b1a/32.png) [@lgao](https://www.ruby-forum.com/u/lgao)\
**Post date:** [April 20, 2006, 9:52am UTC](https://www.ruby-forum.com/t/table-that-have-many-to-may-relationship-to-itself/58290/1 "2006-04-20T09:52:49Z")

</div>

In a social netowrk data model, users belongs other users, and can have  
many friends as users, so it is a many to many relatioship.

the class definition could be

class User \< ApplicationController  
has\_mang\_ang\_belongs\_to users

But how it looks like in the mysql database tables in a “joined” users  
table.

The question really is: what is the table looks like when a model has  
many and belongs itself.

thx

---

<div class="post-metadata">

**Author:** ![lgao](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/l/e68b1a/32.png) [@lgao](https://www.ruby-forum.com/u/lgao)\
**Post date:** [April 20, 2006, 10:09am UTC](https://www.ruby-forum.com/t/table-that-have-many-to-may-relationship-to-itself/58290/2 "2006-04-20T10:09:39Z")

</div>

Hi,

This example is right out of the Rails Recipes book by Chad F.  
([http://www.pragmaticprogrammer.com/titles/fr\_rr/index.html](http://www.pragmaticprogrammer.com/titles/fr_rr/index.html)):

Assume that you have people and people have friends. Just as you’ve  
described, this is a habtm relationship that refers back to the same  
table. Whenever you have a habtm, you need a join table. Here’s a  
(partial) migration that describes the two tables:

create\_table :people do |t|  
t.column “name”, :string  
end  
create\_table :friends\_people, :id =\> false do |t|  
t.column “person\_id”, :integer  
t.column “friend\_id”, :integer  
end

And now here is the ActiveRecord model:

class Person \< ActiveRecord::Base  
has\_and\_belongs\_to\_many :friends,  
:class\_name =\> “Person”,  
:join\_table =\> “friends\_people”,  
:association\_foreign\_key =\> “friend\_id”,  
:foreign\_key =\> “person\_id”  
end

brian

---

<div class="post-metadata">

**Author:** ![lgao](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/l/e68b1a/32.png) [@lgao](https://www.ruby-forum.com/u/lgao)\
**Post date:** [April 20, 2006, 10:17am UTC](https://www.ruby-forum.com/t/table-that-have-many-to-may-relationship-to-itself/58290/3 "2006-04-20T10:17:35Z")

</div>

You’re talking about a self-referential many-many relationship. The  
Rails Recipes book has an example of how to do this, plus there are a  
few other things in various places. Try googling “ruby rails  
self-referential”
