Cot*_*Joe 13 ruby-on-rails ruby-on-rails-4
该Order模型:
class Order < ActiveRecord::Base
has_many :sales, dependent: :destroy, inverse_of: :order
end
Run Code Online (Sandbox Code Playgroud)
has_many Sales:
class Sale < ActiveRecord::Base
belongs_to :order, inverse_of: :sales
validates :order, :product, :product_group, :presence => true
before_create :price
def price
mrr = Warehouse.where(:product => self.product).pluck(:mrr).shift.strip.sub(',', '.').to_f
self.price = mrr * self.quantity.to_f
end
end
Run Code Online (Sandbox Code Playgroud)
当我销毁一个Order,相关的Sales也应该被销毁,但是这样做时我遇到了一个错误:
RuntimeError in OrdersController#destroy
Can't modify frozen hash
Run Code Online (Sandbox Code Playgroud)
这一行突出显示:self.price = mrr * self.quantity.to_f.
Sale手动逐步销毁所有关联的记录可以正常工作而不会出错.在没有Sale关联之后,我也可以破坏Order记录.
有任何想法吗?
And*_*eko 20
在突出显示的行上,您应该确保sale在更新其price属性时不会销毁它:
self.price = mrr * quantity.to_f unless destroyed? # notice, no need for self before quantity
# or
write_attribute(:price, mrr * quantity.to_f) unless destroyed?
Run Code Online (Sandbox Code Playgroud)