我的用户有以下型号:
class User < ActiveRecord::Base
has_many :facebook_friendships
has_many :facebook_friends, :through => :facebook_friendships, :source => :friend
def mutual_facebook_friends_with(user)
User.find_by_sql ["SELECT users.* FROM facebook_friendships AS a
INNER JOIN facebook_friendships AS b
ON a.user_id = ? AND b.user_id = ? AND a.friend_id = b.friend_id
INNER JOIN users ON users.id = a.friend_id", self.id, user.id]
end
end
class FacebookFriendship < ActiveRecord::Base
belongs_to :user
belongs_to :friend, :class_name => 'User'
end
如果 id 为 53 的用户和 id 为 97 的用户是彼此的朋友,那么您将在数据库的 facebook_friendships 表中有行 [53, 97] 和 [97, 53]。这是我用来计算共同朋友的原始 sql 查询:
SELECT users.* FROM facebook_friendships AS a
INNER JOIN facebook_friendships AS b
ON a.user_id = :user_a AND b.user_id = :user_b AND a.friend_id = b.friend_id
INNER JOIN users ON users.id = a.friend_id
我会mutual_friends_with 返回一个关系而不是一个数组。这样,我可以将结果与 where(college: 'NYU') 等其他条件链接起来,并获得 ActiveRecord 的所有优点。有没有好的方法来做到这一点?