Wednesday, August 27, 2014

Unlock ReadOnly Model Object

Phasing some interesting problem after creating record for model which has HasMany relationship.

I have class say 'Category' & 'CategoryOptions'.

Category Has Many CategoryOptions

When i create record for CategoryOption using below syntax it locks the newly created object.

category = Category.first
category_option = category.category_options.create(params[:category_option])

If i do 

category_option.readonly?
=> true

Now i'm trying to update category_option using

category_option.update_attributes(params[:category_option])

but it raises Exception like 

ActiveRecord::ReadOnlyRecord

To remove readonly lock from object use below method

category_option.send(:instance_variable_set, :@readonly, false)

Now try

category_option.readonly?
=> false

category_option.update_attributes(params[:category_option]) works perfectly.

Hope this article will help you to remove Readonly lock from Model Object.

No comments:

Post a Comment