Closed superrordev closed 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
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?
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.
Hello.
I am trying to get the mapping between old and new object after deep clone. For example: author 1 has many books:
Author <Author id: 1, name: 'author 1'>
Book <Book id: 1, name: 'book 1', author_id: 1> <Book id: 2, name: 'book 2', author_id: 1> <Book id: 3, name: 'book 3', author_id: 1>
Cloning dup_author = author.deep_clone include: [:books] dup_author.save!
Result
Author <Author id: 2, name: 'author 1'>
Book <Book id: 4, name: 'book 1', author_id: 2> <Book id: 5, name: 'book 2', author_id: 2> <Book id: 6, name: 'book 3', author_id: 2>
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.