2012-09-17 30 views
1

试图找到相互关系,在朋友关系中,已经有朋友和inverse_friends。但如何结合他们获得共同的朋友?似乎无法弄清楚我试了几个选项,并在网上搜索很久,只是没有看到它rails activerecord,朋友关系+ inverse_friend关系如何获得相互关系?代码包括

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 ? 
+0

如果您发布的表会更容易解决您的问题线索定义,所以我们不必猜测你的模式。 –

回答

3

我不认为你可以定义一个共同的朋友关联。所以,我们来看看一个共同的朋友类方法或范围。

我想我们希望我们所有的朋友,我们都是他们的朋友。

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 ID的方法调用:mutual_friends关联定义。

+0

我有一个粗略的想法这可以用def方法解决,但尝试你的解决方案抛出一个未定义的局部变量或方法'inverse_friends'当我试图访问我的视图中的数据“用户User.mutual_friends puts @user .username end – Rubytastic

+0

减去self.mutual_friends中的“self”。这个工作thx – Rubytastic

+0

如果你想在那里额外的.where语句怎么处理?.where('game_id = 1)。doesent work。thx – Rubytastic

5

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

你不能只是做

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

By mutual_friends,我认为他意味着互惠的友谊。即友谊表中有一个user1.id | user2.id条目和一个user2.id | user1.id条目。 –

+1

这是一个优雅的解决方案。但是有一个小缺点:它返回'Array',所以你可能无法发送你要发送给'ActiveRecord'对象的方法。 (即分页,装饰等) –