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

Get the mapping between old and new object after deep clone #82

Closed superrordev closed 7 years ago

superrordev commented 7 years ago

Hello.

I am trying to get the mapping between old and new object after deep clone. For example: author 1 has many books:

I want mapping hash between old books and new books of duplicated author. mapping = { 1: 4, 2: 5, 3: 6}

How can I get this mapping hash using deep_clone?

Please help me.

moiristo commented 7 years ago

Hello,

I think you can achieve this by enabling the dictionary with a custom hash (see docs). Something like:

dictionary = {}
dup_author = author.deep_clone include: [:books], dictionary: dictionary
dup_author.save!
pp dictionary
superrordev commented 7 years ago

Sorry. This is the output: {:books=>{#<Book id: 1, name: 'book 1'>=>#<Book id: nil, name: 'book 1'>, #<Book id: 2, name: 'book 2'>=>#<Book id: nil, name: 'book 2'>, #<Book id: 3, name: 'book 3'>=>#<Book id: nil, name: 'book 3'>}}

The ids of duplicated objects are nil.

Is there anyway to get the id of duplicated object?

superrordev commented 7 years ago

I'm so sorry. The above was the output before saving. It is showing the mapping between old and new objects.

Yes, it is possible to get ids through that way.

Thank you.