保存前计算嵌套项目

问题描述 投票:0回答:2

具有订单和商品模型。

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,因为尚未创建项目。创建订单时,如何获取将要使用的商品数量?

ruby-on-rails nested cocoon-gem
2个回答
0
投票
def compute_packed_volume
  items.length * 0.1O
end

仅当您明确希望从数据库中获取行数时,才使用#count。否则,您想使用#length来计数内存中的关联,或者使用#size来执行此操作,具体取决于是否加载了关联。

另外,您可能想使用an association callback,以便在将商品添加到订单时对其进行更新。


0
投票

您正在寻找的是“计数器缓存”。它完全实现了您要执行的操作。

© www.soinside.com 2019 - 2024. All rights reserved.