如何在ActiveRecord中进行自反的自我加入关系?

udi*_*dit 4 activerecord ruby-on-rails self-join social-networking

我正在尝试实现一个社交网络风格的友谊模型,我没有太多的运气试图找出那里可用的插件.如果我自己做的话,我想我会更好地学习Rails.所以这就是我所拥有的:

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
Run Code Online (Sandbox Code Playgroud)

irb当我尝试这样的:

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

我收到一个错误:

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?
Run Code Online (Sandbox Code Playgroud)

友谊系统的扩展:

  • 用户可以邀请其他用户成为朋友.
  • 您邀请成为朋友的用户代表invited_friends.
  • 邀请您成为朋友的用户代表inviter_friends.
  • 您的朋友总列表由invited_friends+ 表示inviter_friends.

架构

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

table User
    t.string :name
    t.string :description
Run Code Online (Sandbox Code Playgroud)

ale*_*dev 7

我很惊讶没有人指出最近Ryan Bates 关于这个话题的截屏视频 :)

希望这可以帮助!.

摘自Ryan'......需要在User模型上进行自我引用关联以定义朋友/关注者'