Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove the readonly status from a cloned ActiveRecord model?

I'm writing a feature in my application which is used to clone a whole load of activerecord models and their hierachy. So that I accidentaly don't change the original records I am using the #readonly feature on relations, which is great.

I am using the #clone method to copy those original objects, but there seems to be no way to remove the readonly status on the cloned objects which means I can't save the new objects I have created.

If I load the original objects without using #readonly then it works fine, but then I run the risk of the original records accidentally being deleted.

How can I remove the readonly status?

like image 658
cmrichards Avatar asked Sep 18 '25 09:09

cmrichards


2 Answers

Use instance_variable_set?

my_obj = Object.where(:stuff, :readonly => true)
my_obj.x = "y" 
my_obj.save! #readonly exception
my_obj.send(:instance_variable_set, :@readonly, false)
my_obj.save! #succeeds

I'm not sure if there's a cleaner way though!

like image 62
Joe Pym Avatar answered Sep 21 '25 00:09

Joe Pym


Depending on why you're doing this, it might just be easier to copy the database instead (e.g. mysqldump).

If, on the other hand, you need to do it in ruby, you might like to take a look at the deep_cloneable gem:

original_record.dup :include => [:associated_records]
like image 24
RobinGower Avatar answered Sep 21 '25 00:09

RobinGower