在rails3中创建非定向自引用关联

时间:2011-01-21 05:53:48

标签: ruby-on-rails-3 associations

我正在创建一个rails3应用,它将包含用户将其他用户添加为朋友的功能。这种关系应该表现得像facebook友谊,其中友谊必须是相互的,而不是twitter友谊,其中用户可以在没有互惠的情况下与另一个用户交朋友。如果不在两个用户之间创建两个单独的关系,我不知道如何做到这一点。这是我到目前为止所做的:

class User < ActiveRecord::Base
  has_many :friendships
  has_many :friends, :through => :friendships
end

class Friendship < ActiveRecord::Base
  belongs_to :user
  belongs_to :friend, :class_name => "User", :foreign_key => "friend_id"
end 

为了建立友谊,我打电话给:

@user1.friends << @user2

然而,这只会在一个方向上创造关系。 @ user2.friends仍然是空的。我知道如何使其正常工作的唯一方法就是致电:

@user1.friends << @user2
@user2.friends << @user1

2 个答案:

答案 0 :(得分:1)

看看本教程是否有帮助:

http://asciicasts.com/episodes/163-self-referential-association

特别是“反向关系”部分:

“在创建自我引用关系时,重要的是要记住我们只创建关系的一方......我们需要两条友谊记录来建立相互的友谊。”

class User < ActiveRecord::Base   

  has_many :friendships   
  has_many :friends, :through => :friendships   

  has_many :inverse_friendships, :class_name => "Friendship", :foreign_key => "friend_id"   
  has_many :inverse_friends, :through => :inverse_friendships, :source => :user   

  #rest of class omitted. 
end

答案 1 :(得分:0)

也许你应该使用before_save_collection_association回调?它会给你一些额外的能力。