![](/img/trans.png)
[英]Friends checkins with facebook graph api and rails - APIError
[英]Struggling with a complex Rails 3 query (need: user.friends.checkins)
我正在开发一个社交网络应用程序,并试图构建一个复杂的查询,该查询可以有效地从数据库中提取所有用户朋友的签到。 基本上我需要:“ user.friends.checkins”
我已经重新创建(以简化形式)下面的数据结构以供参考,并包括一些已经找到的解决方案,但是我觉得我的解决方案不是最优的。 我希望有人可以指出一种更好的方法。
我首先尝试了此方法,但效果不错,但考虑到用户通常每个人都有+1000个朋友,因此速度太慢了:
=> Checkin.where(:user_id => self.friends)
然后,我尝试了此方法,它也可以工作并且速度更快,但是感觉很草率:
=> Checkin.joins(:user).joins('INNER JOIN "friendships" ON
"users"."id" = "friendships"."friend_id"').where(:friendships =>
{:user_id => 1})
您能提供的任何帮助将不胜感激! 提前致谢!!!
===数据结构===
Users table has columns: id, name
Friendships table has columns: user_id, friend_id
Checkins table has columns: id, location, user_id
===型号===
class User
has_many :friendships
has_many :friends, :through => :friendships
has_many :checkins
end
class Friendship
belongs_to :user
belongs_to :friend, :class_name => 'User'
end
class Checkin
belongs_to :user
end
第一个查询应该为您服务。 将索引添加到查询中的外键字段。
到目前为止,我发现的最佳解决方案:
Checkin.joins(:user => :friendships).where('friendships.friend_id' => self.id)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.