2016-02-26 28 views
0

我有一个数据库(PG)的用户,每个用户都属于一个组织。Rails数据库 - 针对特定数据库请求优化代码

然后项目,其中每个属于一个用户。

每个项目都有与其关联的“点”。

我希望找到的前3名用户得分超过过去7天的最高分......

这是我迄今为止得到了 - 但我认为这是非常缓慢的 - 更好的想法?

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

您应该可以在使用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和它们的总点数。

+0

应该提到的问题(现在编辑) - 使用Postgres数据库。如果这仍然有效? – Jmohey

+0

它应该尝试一下。 – Baldrick

+0

“ActiveRecord :: ConfigurationError异常:在Item上找不到名为”users'的关联“就是它提供的内容..? – Jmohey