Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rails, activerecord sum then order

i have a Job model that belongs_to User, and User has_many jobs. I want to create an AR query that calculates the total number of work days per user, then orders in Descending order.

I have this so far, but is giving me an error: (column "Job.id" must appear in the GROUP BY clause or be used in an aggregate function)

@work_days = Job.group(:user).order('SUM(total_days)')

I can't seem to get the .order method to work - is there something I am missing? Thanks in advance!

like image 711
gitastic Avatar asked Dec 03 '22 18:12

gitastic


2 Answers

You could write your query :-

Job.group(:user_id).select('SUM(total_days) as tot').order('tot desc')
like image 110
Arup Rakshit Avatar answered Dec 07 '22 22:12

Arup Rakshit


With slight variation from earlier

Job.group(:user_id).order('sum_total_days DESC').sum(:total_days)
like image 31
Pritesh Jain Avatar answered Dec 08 '22 00:12

Pritesh Jain