如何将每个价格添加到当前价格? [英] How do I add each price to the current price?
本文介绍了如何将每个价格添加到当前价格?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试编写一个方法来查找每个价格并将其添加到当前价格中.
I am trying to write a method that will find each price and add it to the current price.
报价.rb:
class Quote < ActiveRecord::Base
has_many :items
def calc_price
sum = 0
items.each do |item|
item.price
end
sum = (item1 + item2 etc)
end
end
推荐答案
这里有一个关于较新的 Ruby 的不错的功能:
Here's a nice feature about the more current Rubies:
values = [1,2,3,4,5]
values.inject(:+) # => 15
现在,也就是说,你正在使用一个数据库,所以它sum
记录.来自文档:
Now, that said, you're working with a database, so have it sum
the records. From the documentation:
计算给定列上的值的总和.返回的值与列的数据类型相同,如果没有行,则返回 0.有关选项的示例,请参阅计算.
Calculates the sum of values on a given column. The value is returned with the same data type of the column, 0 if there’s no row. See calculate for examples with options.
Person.sum('age') # => 4562
这篇关于如何将每个价格添加到当前价格?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文