Many to Many Relationship with One Model

Hey everyone,

I'm working on allow users to follow other users in my app so they can
receive updates to what all their friends are doing (like Facebook/
Twitter). I'm wondering on how the relationship would be for the
model. Sounds like a HABTM type of association, but how would I go
about doing it for only one model?


I’ll start w/ the User class.

class User < ActiveRecord::Base
has_and_belongs_to_many :friends,
:class_name => “User”, # [1]
:join_table => “users_friends”, # [2]

:foreign_key => "user_id", # [3]
:association_foreign_key => "friend_id" # [4]


[1] Specify the class name since it differs from the association name.
[2] Specify the join table since you’ll name it something other than users_users, which is what Rails would assume.

[3] Specify the foreign key back to this user; not necessary as Rails will assume it in this case, but I thought I’d show it.
[4] Specify the foreign key that will hold the ids of this user’s friends.

Here’s the migration to create the join table.

class … < ActiveRecord::Migration
def self.up
create_table :users_friends, :id => false, :force => true do |t|
t.integer :user_id,
t.integer :friend_id

def self.down
drop_table :users_friends

As you can see, it’s just a simple join table for tracking the relationship from user to user (friend).

I’m sure you’ll want to tweak the User class and migration a bit, but I hope you get the idea.


That's exactly was I was trying to pull off, perfect explanation!

Thanks a lot Craig!

I agree, I was trying to figure out how to do exactly the same thing!
Great explanation.