3

I have an after_destroy model callback that regenerates cache after the model instance has been destroyed. It does this by calling open("http://domain.com/page-to-cache") for as many pages as need to be re-cached.

The problem is that the model instance apparently isn't fully destroyed yet at this time, because those open url requests still register its presence, and the regenerated cache looks exactly like the pre-destroy cache. How can I run those calls after the model instance has been actually destroyed?

glortho
  • 13,120
  • 8
  • 49
  • 45

2 Answers2

5

You may be able to use an after_commit callback to do something after the entire transaction has gone through to the database. This is different depending on the version of Rails you're using (2.3.x versus 3.x.x), but is essentially something like the following:

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

You can read some documentation about the Rails 3 after_commit callback here. If your version of Rails doesn't have an after_commit hook, you can try using this gem which will provide the functionality.

Mike Trpcic
  • 25,305
  • 8
  • 78
  • 114
  • Thanks, Mike. I'm using 2.3.8. I tried this in the model and it never fired. I'll try it in the sweeper and see what happens... – glortho May 11 '11 at 19:03
  • No, still didn't fire. Even though the sweeper is inheriting from ActionController::Caching::Sweeper, it is set up to observe my model and thus should act the same as your observer, right? Appreciate the thoughts... – glortho May 11 '11 at 19:10
  • 1
    I believe in Rails 2.3.8 there is no default `after_commit` hook. Google for a plugin/gem that extends ActiveRecord to provide this functionality. – Mike Trpcic May 12 '11 at 13:42
  • 1
    If anyone has trouble finding a gem/plugin, I recommend https://github.com/freelancing-god/after_commit for use in Rails 1 and 2. – severin Jun 29 '11 at 07:20
  • The repo for after_commit has changed. The new URL is https://github.com/pat/after_commit – Chris Bloom Feb 28 '14 at 15:45
0

You could try adding an after_save callback like:

after_save :my_after_save_callback

def my_after_save_callback
  do_something if destroyed?
end
Austin
  • 3,860
  • 3
  • 23
  • 25