我有以下设置。
Invoice has_many Jobs has_many Tasks belongs_to user
我想获得所有有任务User
的 sInvoice
并总结它们的数量
class Invoice < ActiveRecord::Base
has_many :jobs
end
class Job < ActiveRecord::Base
belongs_to :invoice
has_many :tasks
end
class Task < ActiveRecord::Base
belongs_to :job
belongs_to :user
end
这是我得到的
@invoice = Invoice.find(params[:id])
jobs = @invoice.jobs.joins(:tasks)
.select('tasks.user_id, (sum(tasks.quantity)*jobs.price) as total')
.group('tasks.user_id, jobs.id')
.order('tasks.user_id')
我明白了,这与我想要的很接近
- !ruby/object:Job
attributes:
user_id: '1'
total: '60.00'
- !ruby/object:Job
attributes:
user_id: '1'
total: '50.00'
- !ruby/object:Job
attributes:
user_id: '2'
total: '120.00'
- !ruby/object:Job
attributes:
user_id: '2'
total: '100.00'
我如何将user_id
其分组并总结总数,以便我有这样的东西?
user_id: 1
total: 110
user_id: 2
total: 220