moiristo / deep_cloneable

This gem gives every ActiveRecord::Base object the possibility to do a deep clone that includes user specified associations.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

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

superrordev opened this issue · comments

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?

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.

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

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).

I understand clearly.
Thanks.