【发布时间】:2018-09-14 05:16:39
【问题描述】:
我有这个带有 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 不起作用。
如果有人知道这件事,请告诉我。
【问题讨论】: