Search code examples
ruby-on-railsrubyactiverecordruby-on-rails-5ruby-on-rails-6

How to group and sum all currencies


I hope the title is correct. I need to sum all currencies ie all of $, £ etc, but not to combine all into one sum.

Basically if I have 2x $4 and 3x £10, that will be $8 and £30

I have an Income model with attributes :currency (string) and :amount (float):

What I have works but I feel it can refactor a bit:

Income.all.group(:currency).count.map do |k,v|
  Income.where(currency: k).map.sum(&:amount)
end

That gives me an array of the total. Ok-ish. I needed a more nicer format such as an Hash:

{
  USD => 8.0,
  GBP => 30.0
}

Possible? How, please?


Solution

  • I think the following would do:

    Income.group(:currency).sum(:amount)
    

    The SQL would looks like:

    SELECT SUM(income.amount) AS sum_amount, currency AS currency
      FROM income
      GROUP BY income.currency