与Rails的相互关系

时间:2011-05-12 13:52:18

标签: ruby-on-rails ruby-on-rails-3

我正在关注railscasts的第163集,并且它允许用户表示另一个用户是否有朋友,但这或多或少都是。

我想找一个帮助者,找出用户是否是他们的朋友。

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

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

@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.

我该怎么做?

感谢。

1 个答案:

答案 0 :(得分: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)