我有以下設置。將數組分組並獲得總和
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