Unfreeze a frozen ActiveRecord

Posted . Visible to the public.

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

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.

Henning Koch
Last edit
Henning Koch
License
Source code in this card is licensed under the MIT License.
Posted by Henning Koch to makandra dev (2015-04-21 09:59)