Justin
Justin

Reputation: 4940

Rails limit query after order and improve performance

Sorry for the vague title

I have a query where I'm getting a list of the 5 users with the highest rating_number which is an indexed column in the user table.

When I get the list of these users based on their rating_number then call the .limit(5) method, it will just take 5 users and then on those five users put them in order of rating_number, even though these users aren't the ones with the highest rating_number.

Here is the current scope, but I know I can improve the performance of this query so please let me know how to if you know, because I have a few of these queries on one page and it's performance is terrible.

in my user model

scope :top_five_users, -> do
  results = User.all
  results.order('rating_number DESC')
  results.limit(5)
end

Thanks!

Upvotes: 0

Views: 392

Answers (1)

Siva
Siva

Reputation: 8058

You dont need to use .all

User.order('rating_number DESC') 

Above is enough to obtain the highest rated users

And to limit 5 users

scope :top_five_users, -> do
  User.order('rating_number DESC').limit(5)
end

Upvotes: 2

Related Questions