简体   繁体   中英

Rails 5 ranking of users by number of tasks

I have 2 models User and Task

User -> has_many :tasks
Task -> belongs_to :user

I want to make a ranking of users by number of tasks

Expected output:

[['jhon', 120],['peter', 115],['mary', 101],....]

my attempt:

User.left_joins(:tasks).group(:id).order('count(tasks.id)').limit(20) ---> not working, can't get the user name

Update your query to

User.left_joins(:tasks).group(:id).select('users.name, count(tasks.id) as tasks_count').order('tasks_count DESC').limit(20).map{ |user| [user.name, user.tasks_count] }

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