当嵌套字段与 cocoon 关联时无法工作 before_validation gem

Can't work before_validation when nested field is delated with cocoon gem

我有这个迁移和订单模型,order_detail 有 cocoon gem。

class CreateOrders < ActiveRecord::Migration[5.0]
  def change
    create_table :orders do |t|
      t.integer :total_price
      t.timestamps
    end
  end
end

class CreateOrderDetails < ActiveRecord::Migration[5.0]
  def change
    create_table :order_details do |t|
      t.integer :subtotal_price
      t.integer :unit_price
      t.integer :quantity
      t.references :order, foreign_key: true
      t.timestamps
    end
  end
end

class Order < ApplicationRecord
  has_many :order_details, inverse_of: :order, dependent: :destroy
  before_validation :calculate_order_price
  accepts_nested_attributes_for :order_details, :reject_if => :all_blank, :allow_destroy => true

  def calculate_order_price
    order_details.each(&:calculate_order_detail_price)
    self.total_price = order_details.map(&:subtotal_price).sum
  end
end

class OrderDetail < ApplicationRecord
  belongs_to :order
  def calculate_order_detail_price
    self.subtotal_price = unit_price * quantity
  end
end

当我在添加或编辑嵌套字段后保存记录时,效果很好。但是如果我编辑 delate 嵌套字段,calculate_order_price 不起作用。

如果有人知道这件事,请告诉我。

有一个选项 :touch 将确保在更新时父设置 updated_at (或其他字段)但它不会 运行 验证。然而,还有一个选项 :validate(但不完全确定它会在销毁时被调用):

 belongs_to :order, validate: true 

否则,如果这些都不起作用,你可以做类似

的事情
class OrderDetail < ApplicationRecord 

  belongs_to :order 

  after_destroy :trigger_parent_validation

  def trigger_parent_validation 
    if order.present? 
      order.validate 
    end
  end 
end