I have a database (PG) of users, each of which belong to an organisation.
And then items, each of which belong to a user.
Each item has 'points' associated with it.
I am looking to find the top 3 users with the most points scored over the last 7 days...
Here is what I have got thus far - but I think it is very slow - any better ideas?
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]
And then do the same for the second and the third highest...
I realise there are probably a lot of ways to speed this up so any feedback would be great.