How do I do reflexive self-join relationships in ActiveRecord?

udit picture udit · Jun 23, 2009 · Viewed 9.4k times · Source

I'm trying to implement a social networking style friendship model and I didnt have much much luck trying to figure out the plugins available out there. I think I'll learn Rails better if I do it myself. So here's what I have :

class User < ActiveRecord::Base
  has_many :invitee_friendships ,
           :foreign_key => :friend_id,
           :class_name => 'Friendship'

  has_many :inviter_friends,
            :through => :invitee_friendships

  has_many :inviter_friendships ,
           :foreign_key => :user_id,
           :class_name => 'Friendship'

  has_many :invited_friends,
            :through => :inviter_friendships

end

class Friendship < ActiveRecord::Base
  belongs_to :user
  //I think something needs to come here, i dont know what
end

In irb when I try this:

friend1  = Friend.create(:name => 'Jack')
friend2  = Friend.create(:name => 'John')
bff = Friendship.create(:user_id =>1, :friend_id => 2)
f1.invited_friends

I get an error:

ActiveRecord::HasManyThroughSourceAssociationNotFoundError:
Could not find the source
association(s) :invited_friend or
:invited_friends in model Friendship. 
Try 'has_many :invited_friends,
:through => :invited_friendships,
:source => <name>'.  Is it one of
:user?

Expanation of friendship system:

  • A user can invite other users to become friends.
  • Users who you invited to become friends are represented by invited_friends.
  • Users who invited you to become friends are represented by inviter_friends.
  • Your total friend list is represented by invited_friends + inviter_friends.

Schema

table Friendship
      t.integer :user_id
      t.integer :friend_id
      t.boolean :invite_accepted
      t.timestamps

table User
    t.string :name
    t.string :description

Answer

alex.zherdev picture alex.zherdev · Jun 23, 2009

I'm surprised no one has pointed to the recent Ryan Bates's screencast on the topic :)

Hope this helps!.

Excerpt from Ryan '... requires a self-referential association on the User model to define friends/followers'