如何在Rails中获得真正的after_destroy?

发布于 2024-11-06 04:13:54 字数 234 浏览 6 评论 0原文

我有一个 after_destroy 模型回调,可以在模型实例被销毁后重新生成缓存。它通过为需要重新缓存的页面调用 open("http://domain.com/page-to-cache") 来实现此目的。

问题是模型实例此时显然还没有完全销毁,因为那些打开的 url 请求仍然注册它的存在,并且重新生成的缓存看起来与销毁前的缓存一模一样。在模型实例实际被销毁后,如何运行这些调用?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

春庭雪 2024-11-13 04:13:54

您可以在整个事务处理完数据库后使用 after_commit 回调执行某些操作。根据您使用的 Rails 版本(2.3.x 与 3.xx)的不同,这会有所不同,但本质上类似于以下内容:

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

您可以阅读一些有关 Rails 3 after_commit 回调的文档 < a href="http://edgeapi.rubyonrails.org/classes/ActiveRecord/Callbacks.html" rel="nofollow">此处。如果您的 Rails 版本没有 after_commit 钩子,您可以尝试使用这个 gem< /a> 将提供该功能。

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.

风尘浪孓 2024-11-13 04:13:54

您可以尝试添加 after_save 回调,例如:

after_save :my_after_save_callback

def my_after_save_callback
  do_something if destroyed?
end

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
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文