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
在卖方。rb我有
def total_item_cost
items.to_a.sum(&:sale_price)
end
This works fine if all the items have a sale price.
However, if they haven't been sold yet, sale_price
is nil and the total_item_cost
breaks.
如果所有的商品都有打折的话,这是可行的。但是,如果还没有出售,sale_price是nil, total_item_cost会中断。
In my app, sale_price
can be either a nil or a zero.
在我的应用中,sale_price可以是nil,也可以是零。
In my total_item_cost
method, how can I treat nil
values as zeros?
在total_item_cost方法中,如何将nil值视为零?
3 个解决方案
#1
31
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
.
方法像#to_f和#to_i将nil变为0。
#2
39
items.map(&:sale_price).compact.sum
or
或
items.map(&:sale_price).sum(&:to_i)
#3
1
Reject the nil values. items.to_a.reject{|x| x.sales_price.nil?}.sum(&:sale_price)
拒绝零值。items.to_a。反对{ x | | x.sales_price.nil ? } .sum(&:sale_price)
#1
31
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
.
方法像#to_f和#to_i将nil变为0。
#2
39
items.map(&:sale_price).compact.sum
or
或
items.map(&:sale_price).sum(&:to_i)
#3
1
Reject the nil values. items.to_a.reject{|x| x.sales_price.nil?}.sum(&:sale_price)
拒绝零值。items.to_a。反对{ x | | x.sales_price.nil ? } .sum(&:sale_price)