ruby-on-railsrubyjsonruby-on-rails-4after-save

How to sum JSON objects data in Rails using after_save?


I'm storing daily orders inside daily_orders table. Inside that table, I've total column and special_kitchen_orders column (type: JSON).

Right now, when I run this into my console:

ap DailyOrder.first.special_kitchen_orders

I get this back:

[
    [0] {
         "name" => "pizza",
          "qty" => 1,
        "price" => 10
    },
    [1] {
         "name" => "burger",
          "qty" => 1,
        "price" => 20
    },
    [2] {
         "name" => "cake",
          "qty" => 1,
        "price" => 30
    }
]

I was thinking to use after_save to calculate sum of all objects price but I've no idea how to make it.

In this example, the total should be 60 (10 + 20 + 30).

How to sum all objects price after saving the record and put it inside the total column using after_save?

Note: ap is from awesome_print gem.

SOLVED

I just found the idea after reading this article. Thanks Sergio Tulentsev for pointing this reduce thing to me. It's totally new thing for me.

def total(array)
  array.reduce(0) do |sum, num|
    sum += num
  end
end


total([1,2,3])
# => 6

Solution

  • It's as simple as this

    special_kitchen_orders.reduce(0) do |memo, order| 
      memo + order['qty'] * order['price']
    end
    

    Also you might want to do this in a before_save, not after_save.