2011-05-12 89 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