awvidmer
awvidmer

Reputation: 155

Adding a Money object transformation to a sum query in Rails 3.1

Another noob question that seems like it should be simple:

Thanks to the help received here, I can easily get a sum of selected transactions:

@trip_hash = transactions.sum(:amount_cents, :group => :trip_id)

The issue, however, is that the :amount_cents column represents a raw Money object that needs to be transformed before summing in order to accommodate currency exchange. The Money "composed of" Procs look like this:

composed_of :amount, 
          :class_name => "Money", 
          :mapping => [%w(amount_cents cents), %w(currency currency_as_string)], 
          :constructor => Proc.new { |cents, currency| Money.new(cents || 0, currency || Money.default_currency) }, 
          :converter => Proc.new { |value| value.respond_to?(:to_money) ? value.to_money : raise(ArgumentError, "Can't convert #{value.class} to Money") }

I can easily call:

transactions.map(&:amount).inject(:+)

to get a transformed grand total, but I can't figure out how to do it in the context of the groupings.

Many thanks, again, for the help!

Upvotes: 1

Views: 1269

Answers (1)

awvidmer
awvidmer

Reputation: 155

Took a lot of canoodling and reading, but finally figured out the following:

trip_hash = bankroll.transactions.group_by(&:trip_id).map {|tr,t| Hash[tr, t.map(&:amount).inject(:+)]}

=>[{0=>#<Money cents:137693 currency:USD>}, {7=>#<Money cents:-39509 currency:USD>}, {10=>#<Money cents:50009 currency:USD>}]

Map within the map did it! Hashifying makes it view friendly, and it retains the Money object for formatting purposes....

Upvotes: 3

Related Questions