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?
[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.