我正在研究社交网络应用程序,并试图构建 复杂的查询,该查询有效地将所有用户的朋友的登录信息从 数据库。基本上我需要:使用复杂的Rails 3查询(需要: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
与第一解决方案的问题在于,它需要3秒钟的加载由“self.friends”返回500-1000 ActiveRecord对象。它不是SQL很慢(SQL只需要2-3ms),它是ActiveRecord。我刚刚发布了另一个解决方案,我发现这似乎是一种改进。 – 2010-10-15 07:24:48