我有以下设置。将数组分组并获得总和
Invoice has_many Jobs has_many Tasks belongs_to user
我想所有User
S代表的Invoice
有任务,并总结了它们的数量
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
解决这个请你澄清你的模型之间的关系。如何连接任务和作业? – gabrielhilal 2013-03-26 12:18:32
这似乎是一个更适合原始SQL或Arel而不是使用ActiveRecord的工作。 – 2013-03-26 12:18:35
你不是在想SQL查看吗? – 2013-03-26 14:28:30