Search code examples
ruby-on-railsrubypostgresqlruby-on-rails-5

Sum of table attributes when value is string


I've never came 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?


Solution

  • Processing database with Ruby is memory inefficient.

    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 DECIMAL)")
    
    1. coalesce will replace null values with '0'
    2. sum all values casted to DECIMAL.