简体   繁体   中英

Ruby on Rails: How to limit the results of sorting active record results

I have the following code, which sorts Users by number of posts. How can I limit this to the top 5 results?

<%= @top5 = User.all.sort{|a,b| a.questions.where(ques_num: 2).count <=> b.questions.where(ques_num: 2).count}.reverse %>

you can simply add .first(5) or .last(5).reverse

<%= @top5 = User.all.sort{|a,b| a.questions.where(ques_num: 2).count <=> b.questions.where(ques_num: 2).count}.reverse.first(5) %>

or

<%= @top5 = User.all.sort{|a,b| a.questions.where(ques_num: 2).count <=> b.questions.where(ques_num: 2).count}.last(5).reverse %>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM