Sylar Sylar - 2 months ago 12
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
amount
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
float
?

Answer

Processing database with Ruby is super memory ineffective!

First shot:

Model
  .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.
Comments