10

我有以下设置。

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
4

3 回答 3

2

谢谢你的回答。

我设法解决了这个问题

user_totals = jobs.to_a.group_by(&:user_id).map{ |user_id,jobs| {:user_id => user_id.to_i, :total => jobs.sum {|j| j.total.to_f} }} 
=> [{:user_id=>1, :total=>110.0}, {:user_id=>2, :total=>220.0}]
于 2013-03-27T08:19:32.323 回答
0

利用group_by

Hash[jobs.group_by(&:user_id).map {|user_id, jobs|  [user_id, jobs.reduce{ |m, job| m+job.total] }]

类似的东西(我没有测试过,所以它可能无法正常工作)

于 2013-03-26T16:36:17.937 回答
0

也许只是一个简单的每个循环创建一个哈希就可以了?

user_totals = Hash.new(0)
jobs.each do |job|
  user_totals[job.user_id] += job.total
end

这会给你:

user_totals =  {"1":110, "2":220}
于 2013-03-26T16:20:27.193 回答