views:

583

answers:

3

I want to be able to "deep clone" 10 instances of an ActiveRecord model and all its associations into memory, work on them, update the in-memory objects and then, when I've finished, pick one to write back over the original in the database.

  1. How do I deep clone (i.e. .clone but also cloning all associations right down to the bottom of the association tree)? I've assumed so far that I'm going to have to write my own method in the Model.

  2. How can ensure that none of the cloned instances will write back to the database until I'm ready to do so?

If possible I'd like to:-

  1. retain all current IDs as one of my main associations is a *has_many :through* matching the IDs of one model to another

  2. still be able to treat each of the clones as if it were in the database (i.e. *.find_by_id* etc. will work)

Moon on a stick perhaps? ;)

+1  A: 

Not 100% sure of what you are trying to do ...

Models will only be stored in the database if you call the save method. Calling save in an existing model will update the database with any data that has been changed. Associations may be saved also, but it really depends on the type of association and in most cases you will probably need to call save on these models as well.

Toby Hede
A: 

Doh! Sometimes it takes asking the stupid question before you see the obvious answer.

My issue was that I was having to make changes to the associated objects and they weren't showing up when I used those in-memory objects later so thought I had to save. However, you are right. All that was actually happening was that the variables referencing them had gone out of scope and I was therefore accessing the in-database ones instead.

I'll go back through my code and check that this is the case.

Having said that, it doesn't answer my question on the "deep cloning though" ...

Urf
A: 

I've solved our deep cloning issues using DefV's deep cloning plugin : http://github.com/DefV/deep_cloning

It's done everything I've required so far, though as you've found you need to be very watchful of your relationships. My tests have luckily shown this up as an issue and I'm working through it at the moment. I found this post as I was trying to solve it :)

Check out the plugin though, it's been quite handy.

ozzyaaron
Thanks for this. Been a while since I've been on SO so apologies for the late response :)
Urf