更新。尝试这样的事情,它应该工作:
recommended_friends = {}
friends.each do |friend|
if recommeded_friends.length < 10
friend.friends.each do |other_friend|
if other_friend != this_user # exclude myself
recommeded_friends[other_friend] =
(recommeded_friends[other_friend] | 0) + 1
end
end
end
end
recommendend_friends.sort_by{|key, value| value}.reverse
top_ten = recommended_friends.first(10).map{|a| a[0]}
SQL 版本:
Users.find_by_sql([
"SELECT u.*
FROM
(SELECT f2.id, f2.user_1_id u_1_id, f2.user_2_id u_2_id, (count(f1.id)) cnt
FROM friendships f1
JOIN friendships f2 ON f1.user_1_id = f2.user_1_id
OR f1.user_2_id = f2.user_1_id
OR f1.user_2_id = f2.user_2_id
OR f1.user_1_id = f2.user_2_id
WHERE (f1.user_1_id = ? OR f1.user_2_id = ?)
AND (f2.user_1_id <> ? AND f2.user_2_id <> ?)
GROUP BY f2.id, f2.user_1_id, f.user_2_id
HAVING count(f2.id) = 1
ORDER BY cnt DESC) fs
JOIN friendships ff ON ff.user_1_id = fs.u_1_id
OR ff.user_2_id = fs.u_1_id
OR ff.user_2_id = fs.u_2_id
OR ff.user_1_id = fs.u_2_id
JOIN users u ON
CASE WHEN (ff.user_1_id = fs.u_1_id OR ff.user_2_id = fs.u_1_id)
THEN fs.u_2_id ELSE fs.u_1_id END = u.id ",
user.id, user.id, user.id, user.id]).first(10)
理论上应该可以的,试试看。