【发布时间】:2012-05-11 14:46:02
【问题描述】:
我的用户有以下型号:
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 的所有优点。有什么好办法吗?
【问题讨论】:
-
看看 dispora 应用程序 - github.com/diaspora/diaspora。它是一个社交网络应用程序......他们一定已经为您的问题找到了一个不错的解决方案:)。提示:可能你必须在 FacebookFriendship 上添加一些 has_many 关系到 FacebookFriendship
标签: ruby-on-rails activerecord relational-algebra