Help with sorting records in Ruby on Rails
I have a score table that contains two columns: user_id
and score
user_id score
1 200 1 120 1 230 2 300 2 345 3 100 3 40开发者_Python百科 4 350 4 500 ......Score.order('score DESC').limit(3)
lists the top 3 scores. Instead, how would I get the top 3 scores where each user only gets one spot on the list (their highest score).
The high scores from the above table would be:
user_id: 4 score: 500
user_id: 2 score: 345 user_id: 1 score: 230Thanks!
Tim
You should be able to group your query:
Score.order('score DESC').group('user_id').limit(3)
Score.all(:order => 'score DESC', :limit => 3, :group => :user_id)
With new Arel:
Score.group(:user_id).order('score DESC').limit(3)
精彩评论