gpt4 book ai didi

ruby-on-rails - Rails4 : Can't modify frozen hash

转载 作者:行者123 更新时间:2023-12-03 23:26:01 27 4
gpt4 key购买 nike

Order模型:

class Order < ActiveRecord::Base
has_many :sales, dependent: :destroy, inverse_of: :order
end

has_many Sale s:
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

当我摧毁一个 Order ,关联 Sale s 也应该被销毁,但我在这样做时遇到了一个错误:
RuntimeError in OrdersController#destroy
Can't modify frozen hash

该行突出显示: self.price = mrr * self.quantity.to_f .

销毁所有关联的 Sale s 记录手动分步工作,没有错误。后无 Sale不再关联,我可以销毁 Order也记录。

有任何想法吗?

最佳答案

在突出显示的行上,您应该确保 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?

关于ruby-on-rails - Rails4 : Can't modify frozen hash,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34895782/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com