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

not duplicating created_at #54

Closed ivendorin closed 8 years ago

ivendorin commented 8 years ago

I am duplicating a rails object, it is duplicating fine with all details except the created_at value of the object.

Here is the code . I want created_at value of raw_materials and costing_items .

@costing = @old_costing.deep_clone :include => [{style: :images}, {raw_materials: :costing_items} , :other_cost_fixeds, :other_costs, :exchange_rates ], :use_dictionary => true do |original, kopy|
                kopy.remote_picture_url = original.picture_url if kopy.is_a?(Image)
            end
moiristo commented 8 years ago

deep_cloneable uses ActiveRecord#dup, which doesn't preserve timestamps (see http://apidock.com/rails/ActiveRecord/Core/dup). I think the best solution is to set it explicitly in the block, like you did with the picture_url.

ivendorin commented 8 years ago

Since I want to preserve the timestamp of raw_materials and costing_items which are nested , can you please show an example of how to do this ? Is it possible to set the nested attributes original and copy ?

ivendorin commented 8 years ago

It is not clear in the documentation as to how to set block for the association ? Kindly explain .

moiristo commented 8 years ago

The block is called for every dup that has been made, even nested associations. That's why you need to check the type of the dup in the block.

ivendorin commented 8 years ago

What is the syntax to check the type ? I want to check for raw_materials association in the code

@costing = @old_costing.deep_clone :include => [{style: :images}, {raw_materials: :costing_items} , :other_cost_fixeds, :other_costs, :exchange_rates ], :use_dictionary => true do |original, kopy|
kopy.remote_picture_url = original.picture_url if kopy.is_a?(Image)
end
moiristo commented 8 years ago

Something like this:

kopy.created_at = original.created_at if kopy.is_a? RawMaterial