当嵌套字段与茧宝石一起使用时,无法使用before_validation

时间:2018-09-14 05:16:40

标签: ruby-on-rails cocoon-gem

我有这个迁移和带有cocoon gem的order和order_detail模型。

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

在添加或编辑嵌套字段之后保存记录时,它运行良好。但是,如果我编辑以描述嵌套字段,则calculate_order_price不起作用。

如果有人知道这一点,请告诉我。

1 个答案:

答案 0 :(得分:0)

有一个选项: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