Ruby on rails 如何仅从已保存到数据库的项目中获取总计?

Ruby on rails 如何仅从已保存到数据库的项目中获取总计?,ruby-on-rails,ruby,ruby-on-rails-3,activerecord,Ruby On Rails,Ruby,Ruby On Rails 3,Activerecord,在我的Rails应用程序中,我有发票,可以有许多嵌套的项目 class Invoice < ActiveRecord::Base attr_accessible :date, :number, :items_attributes has_many :items accepts_nested_attributes_for :items def total items.map(&:total).sum end end class发票

在我的Rails应用程序中,我有
发票
,可以有许多嵌套的
项目

class Invoice < ActiveRecord::Base

  attr_accessible :date, :number, :items_attributes

  has_many :items

  accepts_nested_attributes_for :items

  def total
    items.map(&:total).sum
  end

end
class发票
如何确保仅对实际保存到数据库中的
项目计算
总计

现在,我的
总计
还包括
项目
,这些项目仅在我的
新建
视图中实例化,但尚未保存到数据库中

谢谢你的帮助

def total
  items(true).map(&:total).sum
end
true
强制重新加载
项。或:

def total
  items.select(&:persisted?).map(&:total).sum
end

persistend?
true
,如果对象在数据库中(不是新的,也不是删除的)。

我只会为total(默认为true)添加一个参数
persistend\u,以便在您想知道所有行项目的总数而不是数据库中的行项目总数的情况下。例如,如果您在更新发票时出现错误,您可以方便地知道预期的总数。非常感谢。这正是我要找的。
total
items
表中的一个数字字段吗?@Stefan:不是,它是根据物品的
price
quantity
计算出来的。