Rails4: unable to change frozen hash

Order Model:

 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 

When I destroy Order , the Sale associated with it must also be destroyed, but at the same time I encountered an error:

 RuntimeError in OrdersController#destroy Can't modify frozen hash 

This line is highlighted: self.price = mrr * self.quantity.to_f .

Manually deleting all related Sale records works step by step without errors. After no Sale no longer associated, I can also destroy the Order record.

Any ideas?

+7
ruby-on-rails ruby-on-rails-4
source share
1 answer

In the highlighted line, you should make sure that sale not destroyed when the price attribute is updated:

 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? 
+12
source share

All Articles