如何将每个价格添加到当前价格?

问题描述:

我正在尝试编写一个方法来查找每个价格并将其添加到当前价格中.

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