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 web development

Do you need DevOps-experts?

Your development team has a full backlog? No time for infrastructure architecture? Our DevOps team is ready to support you!

  • We build reliable cloud solutions with Infrastructure as code
  • We are experts in security, Linux and databases
  • We support your dev team to perform
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)