对数组进行分组并获得总和

时间:2013-03-26 11:28:13

标签: ruby-on-rails ruby

我有以下设置。

Invoice has_many Jobs has_many Tasks belongs_to user

我想获得User所有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 对此进行分组并总结总数,以便我有这样的内容?

{{1}}

3 个答案:

答案 0 :(得分:1)

感谢您的回答。

我设法用

来解决这个问题
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}]

答案 1 :(得分:0)

也许只是一个简单的每个循环创建一个哈希会做什么?

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

这会给你:

user_totals =  {"1":110, "2":220}

答案 2 :(得分:0)

使用group_by

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

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