开发者

How to get true after_destroy in Rails?

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, becaus开发者_开发知识库e 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?


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.


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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜