在保存模型之前访问所有关联,包括嵌套属性



我有一个Order,一个Item和一个Product模型。

class Order < ApplicationRecord
has_many :items, dependent: :destroy, inverse_of: :order
end
class Item < ApplicationRecord
belongs_to :order
belongs_to :product
end
class Product < ApplicationRecord
has_many :items
end

我需要在before_save回调中计算每个Item有多少个框(item.units/item.product.units_per_box(,但我无法访问嵌套属性,只能访问持久化的项目。

我在Order模型中有这个:

before_save :calculate_boxes, on: [:create, :update]
def calculate_boxes
self.boxes = 0
self.items.each do |item|
self.boxes += item.units / item.product.units_per_box
end
end

但是,我怎么说,它只是计算持久化的项目。

不知道这是否重要,但我正在使用@nathanvda的 Cocoon gem 来管理创建/编辑表单上的嵌套属性。

尝试使用self.items.collect.这应该行得通。另外,我建议您在循环中使用unless item.marked_for_destruction?

最新更新