具有订单和商品模型。
class Order < ApplicationRecord
has_many :items, inverse_of: :order, dependent: :delete_all
before_save do
self.packed_volume = compute_packed_volume
end
private
def compute_packed_volume
items.count * 0.1O
end
end
和
class Item < ApplicationRecord
belongs_to :order, inverse_of: :items
end
问题是item.count等于0,因为尚未创建项目。创建订单时,如何获取将要使用的商品数量?
def compute_packed_volume
items.length * 0.1O
end
仅当您明确希望从数据库中获取行数时,才使用#count
。否则,您想使用#length
来计数内存中的关联,或者使用#size
来执行此操作,具体取决于是否加载了关联。
另外,您可能想使用an association callback,以便在将商品添加到订单时对其进行更新。
您正在寻找的是“计数器缓存”。它完全实现了您要执行的操作。