moiristo / deep_cloneable

This gem gives every ActiveRecord::Base object the possibility to do a deep clone that includes user specified associations.
MIT License
785 stars 89 forks source link

Possibility to fill a dictionary with the structure of the original record. #99

Closed varg90 closed 6 years ago

varg90 commented 6 years ago

Hey! I use deep_cloneable v2.3.2 for my rails (v5.1.4) project.

I faced with a problem cloning a record with a lot of associations (that also have associations among themselves). A regular Project (main record) could have ~50 records (including habtm records), associated with it. Let's say Project has many Ds, each D has many Cs, which belongs_to another C, which has many Bs, which has many As. Furthermore, my HABTM records have polymorphic associations, because A, B, C and D - it's a categories, each has a several models.

So when I added an additional A record and associate it with the B etc, the cloning process starts to take a hours or even a days instead of minutes when I had just one A record.. I don't think that saving ~50 records to DB could take more than one minute.

I'm using use_dictionary: true, validate: false options. I'm also using ActiveRecord::Base.no_touching when I save! deep cloned record. And skip_callback for all the callbacks that I have in my models. I feel like something is happening in the dictionary. In the logs (and server console) it just hangs on the

(0.2ms)  BEGIN
SQL (0.7ms)  INSERT INTO ...
SQL (0.5ms)  INSERT INTO ...
SQL (0.5ms)  INSERT INTO ...
SQL (0.7ms)  INSERT INTO ...
SQL (0.4ms)  INSERT INTO ...

and uses 100% of my CPU for ruby process.

Maybe there is a possibility to collect a dictionary from the original Project record to be able to use it for the deep_clone options, if it could help? I'm afraid that most painful part for deep_cloneable is cloning association chains that include a several polymorphic habtm "chain links". I'd be very grateful if anyone (the gem author or its users) had the same experience and solved this issue still using this gem.

Thanks

moiristo commented 6 years ago

Hello, thanks for your question. Unfortunately I don't have a solution for you yet. The case you describe sounds like it is stuck in a save loop, maybe caused by objects that reference themselves in some way. I don't think deep_cloneable can fix this for you, since it just creates copies on the associations you specify. After that, AR handles how the objects on the associations are persisted on save.

varg90 commented 6 years ago

Thanks for the answer, closed since it’s probably happens because of the specific association scheme in my app