Table that have many-to-may relationship to itself

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

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



This example is right out of the Rails Recipes book by Chad F.

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
create_table :friends_people, :id => false do |t|
t.column “person_id”, :integer
t.column “friend_id”, :integer

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”


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