Sylar Sylar - 1 year ago 66
Ruby Question

Sum of Table atributes when value is string

I've never come across this before. I'm working with a table attribute whos value is a string, not float/int.

Model.first.amount => "58.00"

I need to sum up all amount. What I'm used to, with the
being a float, would be:

Model.all.sum(&:amount) => # total value

Took a wild guess with:

Model.all.sum(&:amount.to_i) # undefined method `to_i' for :amount:Symbol

Is there a clean way to sum up the amount? Or convert the database to

Answer Source

Processing database with Ruby is super memory ineffective!

First shot:

  .pluck(:amount) # will fire sql
  .sum(&:to_f)    # convert to float, operating on resulting Array, not AR and sum

But the most effective way to process database data is SQL of course:

Model.sum("CAST(COALESCE(amount, '0') AS FLOAT)")
  1. coalesce will replace null values with '0'
  2. sum all values casted to Float.
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download