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

How to avoid call_back execution on deep cloned object? #114

Closed fchampreux closed 4 years ago

fchampreux commented 4 years ago

Hi, My application manages business rules, and nested tasks. During a normal creation process, some attributes are initialised in a call-back, such as before_create :set_hierarchy, for eacf object (rule & tasks). For managing versions of a business rule, I deep_clone it. In this case, the before_create call-back must not be executed, so my code is:

BusinessRule.without_callback(:create, :before, :set_hierarchy) do
    @business_rule_version = @business_rule.deep_clone include: :tasks 
    # some stuff
end

This works fine for the business rule, but how can I specify this without_callback clause for the nested tasks? Thanks!

moiristo commented 4 years ago

Hi,

Actually deep_cloneable has not much to do with the creation process, it just builds the hierarchy in memory and lets AR do its thing when you call save. Can't you just do the same as you do for the business rule? Like this:

BusinessRule.without_callback(:create, :before, :set_hierarchy) do
  Task.without_callback(:create, :before, :set_hierarchy) do
    @business_rule_version = @business_rule.deep_clone include: :tasks 
    @business_rule_version.save!
  end
end