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?
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!
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With