4

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
4

1 回答 1

7

我很惊讶没有人指出最近瑞安贝茨关于该主题的截屏视频:)

希望这可以帮助!。

摘自 Ryan '... 需要用户模型上的自引用关联来定义朋友/追随者'

于 2009-06-23T20:47:00.717 回答