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
items.map(&:sale_price).compact.sum
or
items.map(&:sale_price).sum(&:to_i)
Reject the nil values. items.to_a.reject{|x| x.sales_price.nil?}.sum(&:sale_price)
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
.