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

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

class User  :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 

在我尝试这个时:

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

我收到一个错误:

 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 => '. Is it one of :user? 

友谊系统的扩展:

  • 用户可以邀请其他用户成为朋友。
  • 您邀请成为朋友的用户由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 

我很惊讶没有人指出最近Ryan Bates关于这个主题的截屏video 🙂

希望这可以帮助!。

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