2011-05-12 79 views
0

我正在关注railscasts的163集,它使用户能够表示另一个用户是否有朋友,但那或多或少。与Rails的相互关系

我想找一个帮手来查找用户是否是他们的朋友。

获取彼此为好友的用户列表。

已发送不相互请求的用户列表。

@friends_out = Friendship.where(:user_id=>current_user.id) #users "i" want to be friends with 
@friends_in = Friendship.where(:friend_id=>current_user.id) #users who want to be friend with "me" 
# users who haven't added "my" id to Friendship and vice versa 
# user who are my friend and i'm their friends. 

我该怎么做?

谢谢。

+0

你尝试过什么?如果有的话,请发布不起作用的代码。 – Dogbert 2011-05-12 13:58:01

+0

我不知道如何开始,我可以检索user_id == current_user或friend_id ==当前和两者的友谊,并从朋友模型访问朋友或用户? – 2011-05-12 14:05:56

+0

在控制台中的工作方式如预期:) f = Friendship.where(:user_id => 2).first.friend – 2011-05-12 14:10:58

回答

2
class User < ActiveRecord::Base 
    def friends_with?(user) 
    self.friendships.where(:friend_id => user.id).any? 
    end 

    def friends_with_me?(user) 
    user.friendships.where(:friend_id => self.id).any? 
    end 

    def mutual_friends?(user) 
    friends_with?(user) && friends_with_me?(user) 
    end 
end 

然后,你可以这样做:

current_user.friends_with?(other_user) 
+0

does friends_with_me?返回用户的所有朋友? 我了解最后一行,这是为了检查两个用户之间的友谊。 但我如何返回朋友列表? – 2011-05-12 15:53:29

+0

每次你需要找到共同的朋友时,这段代码会发送大量的sql查询,这不是一件好事,相反如果你可以做一次这些计算并将共同的朋友保存在另一个表中,那么它会更好,这样它就可以轻松访问。您也可以运行一项工作,在用户建立连接时更新这些共同的朋友 – Magesh 2012-03-22 04:18:43