Rails4: Can't modify frozen hash
Asked Answered
M

3

18

The Order model:

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

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

When I destroy an Order, the associated Sales should also be destroyed, but I ran into an error when doing so:

RuntimeError in OrdersController#destroy
Can't modify frozen hash

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

Destroying all associated Sales records manually step-by-step works without errors. After no Sale is associated anymore, I can destroy the Order record too.

Any Ideas?

Maronite answered 20/1, 2016 at 9:11 Comment(0)
H
32

On the line that gets highlighted you should make sure that sale is not destroyed when updating its price attribute:

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?
Hurlee answered 20/1, 2016 at 9:32 Comment(1)
Great! I was looking for it to fix a deep bug in the EavHashes gem.Apprehend
L
3

I've encountered the same issue and searched for an answer. Only found the discussion about destroyed; However I've determined that if I create a new active record (find_or_create_by) and then create a second object dependent on the first active record, i get the same error. I resolved it by saving the first active Record before creating/modifying the second. I don't understand why the create is necessary, although I can see why the second record wants the first to exist before it gets saved/modified.

Longcloth answered 18/9, 2018 at 18:6 Comment(0)
D
1

I upgraded Rails from 4.1 to 4.2.5 and got this error when tried save object with tags.

In my case trouble was due gem 'acts-as-taggable-on' which should be upgraded to newer version >= 3.4.

Doggoned answered 23/9, 2018 at 17:21 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.