【问题标题】:Struggling with a complex Rails 3 query (need: user.friends.checkins)挣扎于复杂的 Rails 3 查询(需要:user.friends.checkins)
【发布时间】: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


    【解决方案1】:

    第一个查询应该可以很好地为您服务。为查询中的外键字段添加索引。

    【讨论】:

    • 第一种方案的问题是,加载“self.friends”返回的500-1000个ActiveRecord对象需要3秒。慢的不是 SQL(SQL 只需要 2-3 毫秒),而是 ActiveRecord。我刚刚发布了另一个我发现的似乎是一种改进的解决方案。
    【解决方案2】:

    迄今为止我发现的最佳解决方案:

    Checkin.joins(:user => :friendships).where('friendships.friend_id' => self.id)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-07-28
      • 1970-01-01
      • 2013-02-28
      • 1970-01-01
      • 2023-04-06
      • 2014-08-30
      • 1970-01-01
      相关资源
      最近更新 更多