2016-02-26 43 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