How to get true after_destroy in Rails?

I have a model callback after_destroythat restores the cache after destroying the model instance. He does this by invoking open("http://domain.com/page-to-cache")as many pages as necessary to rewrite.

The problem is that the model instance does not seem to be completely destroyed at this time, because these open url requests still register their presence, and the regenerated cache looks exactly like an extra-destroy cache. How to start these calls after the actual destruction of the model instance?

+3
source share
2 answers

You may be able to use the callback after_committo do something after the entire transaction has passed through the database. It depends on the version of Rails you are using (2.3.x versus 3.xx), but essentially looks something like this:

# model_observer.rb
class ModelObserver < ActiveRecord::Observer
  def after_commit(instance)
    do_something if instance.destroyed?
  end
end

You can read some documentation on the Rails 3 callback after_commit here . If your version of Rails does not have a hook after_commit, you can try this stone , which will provide you with functionality.

+5
source

You can try adding after_save callback, for example:

after_save :my_after_save_callback

def my_after_save_callback
  do_something if destroyed?
end
0
source

All Articles