Many to Many Relationship with One Model

22 views
Skip to first unread message

TeeC

unread,
Aug 28, 2008, 10:47:33 PM8/28/08
to Ruby on Rails: Talk
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?

Thanks,
Tony

Craig Demyanovich

unread,
Aug 29, 2008, 12:23:39 AM8/29/08
to rubyonra...@googlegroups.com
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]
end

[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
    end
  end

  def self.down
    drop_table :users_friends
  end
end

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.

Regards,
Craig

TeeC

unread,
Aug 29, 2008, 2:52:24 PM8/29/08
to Ruby on Rails: Talk
That's exactly was I was trying to pull off, perfect explanation!

Thanks a lot Craig!

On Aug 29, 12:23 am, "Craig Demyanovich" <cdemyanov...@gmail.com>
wrote:

ratibus

unread,
Oct 2, 2008, 4:45:18 PM10/2/08
to Ruby on Rails: Talk
I agree, I was trying to figure out how to do exactly the same thing!
Great explanation.

On Aug 28, 11:23 pm, "Craig Demyanovich" <cdemyanov...@gmail.com>
wrote:
Reply all
Reply to author
Forward
0 new messages