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]
然後做同樣的第二和第三高...
我知道有可能很多的方法來加快這使任何反饋將是巨大的。
應該提到的問題(現在編輯) - 使用Postgres數據庫。如果這仍然有效? – Jmohey
它應該嘗試一下。 – Baldrick
「ActiveRecord :: ConfigurationError異常:在Item上找不到名爲」users'的關聯「就是它提供的內容..? – Jmohey