rails activerecord,friend relation + inverse_friend关系如何获得相互关系? 代码包括在内

试图找到相互关系,在朋友关系中,已经有朋友和inverse_friends。 但如何将它们结合起来以获得共同的朋友呢? 似乎无法弄清楚我尝试了几个选项并在网上搜索了很长时间,只是看不到它

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 

怎么得到一个

 has_many :mutual_friends ? 

我不认为你可以定义一个共同的朋友协会。 那么,让我们看一下共同的朋友类方法或范围。

我认为我们想要所有的朋友,我们是他们的朋友。

 class User 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 def mutual_friends inverse_friends.joins(:friendships).where("friendships.user_id = users.id and friendships.friend_id = :self_id", :self_id => id).all end end 

要做一个关联,这将是你想要做的:

 has_many :mutual_friends, :through => :inverse_friendships, :source => :user, :conditions => ["friendships.user_id = users.id and friendships.friend_id = :self_id", :self_id => id] 

问题在于has_many:mutual_friends关联定义中的id方法调用。

你需要两种模式才能找到共同的朋友吗?

你不能这样做吗?

 @mutualfriends = @user1.friends & @user2.friends 

尝试两个查询的交集在这里是一个线程

两个关系的交叉点