Treating nil as zero in sum function

后端 未结 3 447
遥遥无期
遥遥无期 2020-12-15 04:37

I have a Seller model that has_many Items.

I want to get the total sale price of all of a Seller\'s items.

In seller.rb I have

def total_item         


        
3条回答
  •  隐瞒了意图╮
    2020-12-15 05:13

    One way is:

    items.to_a.sum { |e| e.sale_price.to_i } # or to_f, whatever you are using
    

    Methods like #to_f and #to_i will turn nil into 0.

提交回复
热议问题