在我的Rails应用中,我有invoices
,可以有多个嵌套items
。
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
如何确保total
仅在实际保存到数据库的items
上计算?
目前,我的total
还包含items
,它们仅在new
视图中实例化但尚未保存到数据库中。
感谢您的帮助。
答案 0 :(得分:3)
def total
items(true).map(&:total).sum
end
true
强制重新加载items
。或者:
def total
items.select(&:persisted?).map(&:total).sum
end
如果对象在数据库中(不是新的,未删除),则 persisted?
为true
。