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

时间:2018-09-25 06:16:36

标签: ruby-on-rails nested-attributes cocoon-gem

我有一个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

我需要在Item回调中计算每个item.units/item.product.units_per_box拥有(before_save)的框数,但是我无法访问嵌套的属性,只能访问持久项。 / p>

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来管理创建/编辑表单上的嵌套属性。

1 个答案:

答案 0 :(得分:2)

尝试使用self.items.collect。那应该工作。我也建议您在循环中使用unless item.marked_for_destruction?

相关问题