如何在Rails中实现真正的破坏?

时间:2023-02-04 01:19:45

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.

我有一个after_destroy模型回调,在模型实例被销毁后重新生成缓存。它通过调用open(“http://domain.com/page-to-cache”)来实现这一点,只要有多少页面需要重新缓存。

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?

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

2 个解决方案

#1


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:

您可以使用after_commit回调来在整个事务通过数据库之后执行一些操作。这取决于您使用的Rails版本(2.3)。x和3。x。x,但本质上是这样的

# 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.

您可以在这里阅读一些关于Rails 3 after_commit回调的文档。如果您的Rails版本没有after_commit钩子,您可以尝试使用这个gem来提供这个功能。

#2


0  

You could try adding an after_save callback like:

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

after_save :my_after_save_callback

def my_after_save_callback
  do_something if destroyed?
end

#1


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:

您可以使用after_commit回调来在整个事务通过数据库之后执行一些操作。这取决于您使用的Rails版本(2.3)。x和3。x。x,但本质上是这样的

# 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.

您可以在这里阅读一些关于Rails 3 after_commit回调的文档。如果您的Rails版本没有after_commit钩子,您可以尝试使用这个gem来提供这个功能。

#2


0  

You could try adding an after_save callback like:

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

after_save :my_after_save_callback

def my_after_save_callback
  do_something if destroyed?
end