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

Any way to skip after_create callback? #85

Closed flamontagne closed 6 years ago

flamontagne commented 6 years ago

Is there a way to prevent after_create callbacks from being called on the main record plus all associations when calling deep_clone? I have an after_create method for populating default data, but I don't want it to execute when cloning the record.

Thanks for this great gem.

moiristo commented 6 years ago

Unfortunately not, it isn't rally a concern for this gem. Personally, I'd create an accessor, set that accessor using the optional block of the deep_clone method and check the value before executing the callback. Simple (incomplete) example:

class Node < ActiveRecord::Base
  has_many :nodes
  attr_accessor :skip_callback
  after_create :populate, unless: :skip_callback
end

deep_copy = Node.find(1).deep_clone(include: :nodes) do |original, kopy|
  # This block will be exeuted for every copied record!
  kopy.skip_callback = true
end

deep_copy.save!
flamontagne commented 6 years ago

That's perfect! I didn't know we could use the block to skip the callback. Thanks a lot!

moiristo commented 6 years ago

Glad I could help!