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

Is it possible to set the order of associations while cloning? #88

Closed superrordev closed 6 years ago

superrordev commented 6 years ago
class Template < ApplicationRecord
  has_many :components
  has_many :elements
end

So while cloning of template, I'd like to clone component first and then element next.

How can I implement this using deep_clone?

moiristo commented 6 years ago

Hi,

Could you elaborate? deep_cloneable clones associations by specification order:

# Components are cloned first, elements last
template.deep_clone include: [ :components, :elements ]

It might be that your model has components that in turn have elements as well. In that case it might be that you need to use the dictionary.

superrordev commented 6 years ago

So will it be cloned as order of associations in include attribute?

moiristo commented 6 years ago

Included associations will be cloned in the order defined in include. The order of the records within each association depends on the order in which records are returned by the source association.

You can change the order of associations by using something like has_many :orders, ->{ order(:position) }. It is not possible to force deep_cloneable to clone association records in a different order, but you can always update the copy and its cloned associations afterwards (before persisting it).

superrordev commented 6 years ago

I understand clearly. Thanks.