Rails, activerecord bag, then order
I have a job model that is owned by a user and the user has multiple jobs. I want to create an AR request that calculates the total number of work days per user and then orders in descending order.
I have it so far, but gives me an error: (column "Job.id" should appear in GROUP BY clause or used in 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!
source to share
The existing answers didn't work for me, I had to change the method a bit group
. If I were to use your models (i.e. user), I would need to list every single user attribute in a group method.
i.e. something like:
user_attrs = User.new.attributes.keys.map { |key| "users.#{key}" }.join(",")
Job.group(user_attrs).order('sum_total_days DESC').sum(:total_days)
I don't know if this will actually work in your situation, but after spending an annoying amount of time with this issue, I thought I'd share what worked for me.
source to share