Rails数据库 - 优化特定数据库请求的代码

时间:2016-02-26 10:42:10

标签: ruby-on-rails ruby

我有一个用户数据库(PG),每个用户都属于一个组织。

然后是项目,每个项目都属于一个用户。

每个项目都有与之关联的“积分”。

我希望找到过去7天得分最多的前3位用户......

这是我到目前为止所获得的 - 但我认为这是非常缓慢的 - 任何更好的想法?

organisation_users = User.where(:organisation => current_user.organisation)


    total_data = []
    organisation_users.each do |user|
        points = Item.where("date > ?", Time.new - (7*86400)).where(:user_id => user.id).map{ |h| h.points.to_f}.sum
        user_data = [user.id, points]
        total_data = total_data.push(user_data)
    end

    list_of_points = total_data.map{ |h| h[1]}
    highest_points = list_of_points.sort[-1]
    highest_points_user_id = total_data[list_of_points.find_index(highest_points)][0]

然后对第二和第三最高点做同样的事情......

我意识到可能有很多方法可以加快速度,所以任何反馈都会很棒。

1 个答案:

答案 0 :(得分:1)

您应该可以使用group在单个SQL请求中执行此操作。类似的东西:

top3 = Item.
  select('sum(points) as total_points, users.id')
  joins(:user).
  where(users: {organisation: current_user.organisation}).
  group('users.id').
  order('total_points').
  limit(3)

它返回一个数组,其中包含用户的id及其总分数。