Read more

Unfreeze a frozen ActiveRecord

Henning Koch
April 21, 2015Software engineer at makandra GmbH

You can freeze Show archive.org snapshot any Ruby object to prevent further modification.

Illustration UI/UX Design

UI/UX Design by makandra brand

We make sure that your target audience has the best possible experience with your digital product. You get:

  • Design tailored to your audience
  • Proven processes customized to your needs
  • An expert team of experienced designers
Read more Show archive.org snapshot

If you freeze an ActiveRecord and try to set an attribute you will an error like this:

can't modify frozen hash

This is because ActiveRecord delegates #freeze to its attributes hash.

You can unfreeze most Ruby objects by creating a shallow copy of the frozen object by calling #dup on it:

user = User.find(3)
user.freeze
unfrozen_user = user.dup

Notes for Rails 2 users

There is a bug in Rails 2.3.x where duping an ActiveRecord instance doesn't dup its attributes hash. Hence, you cannot unfreeze the object with dup.

Use the attached initializer to fix that.

Posted by Henning Koch to makandra dev (2015-04-21 11:59)