【发布时间】:2010-10-15 02:59:38
【问题描述】:
我正在开发一个社交网络应用程序,并正在尝试构建 一个复杂的查询,可以有效地拉出所有用户的朋友 从数据库签入。基本上我需要:“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
【问题讨论】:
标签: ruby-on-rails activerecord ruby-on-rails-3