deep_cloneable gem (cloning of activerecord with associations)

103 Views Asked by At

I want to be able to clone objects of class A along with all their (cloned) B, C and D associations.

enter image description here

I have classes A, B C & D:

A has_many Bs

A has_many Cs

A has_many Ds through Bs

B belongs_to A

B has_many Ds

C belongs_to A

C has_many Ds

D belongs_to B

D belongs_to C

So , for example each object of class D has attributes b_id and c_id.

I want to be able to clone objects of class A along with all their (cloned) B, C and D associations.

Following the deep_cloneable documentation, the closest I can get is with:

A.first.deep_clone include: [ {bs: :ds}, :cs ].save

This creates duplicates of the A object and duplicates of its B and C associations (as wanted). The Ds that belong to B are also duplicated and associated with the newly duplicated Bs, but remain associated with the original Cs, not the newly duplicated Cs.

Similarly with

A.first.deep_clone include: [ {bs: :ds}, { cs: :ds} ].save 

An extra set of Ds are duplicated (one set associated with the new Bs but not the new Cs and one set associated with the new Cs but not with the new Cs).

Can I directly achieve what I want with deep_cloneable gem?

1

There are 1 best solutions below

0
Dan SimBed On BEST ANSWER
(A.first.deep_clone include: [ {bs: :ds}, { cs: :ds} ], use_dictionary: true).save

This creates the duplicates I want. The syntax is set out in the documentation under 'The Dictionary', though I can't say I find the description or 'dictionary' terminology easy to follow..