开发者

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: 230

Thanks!

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)
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜