【问题标题】:My custom destroy method does not trigger the default before and after destroy callbacks我的自定义销毁方法在销毁回调之前和之后都不会触发默认值
【发布时间】:2009-12-21 20:21:34
【问题描述】:
我正在编写一个为模型提供绘图的插件。删除操作是可草拟的操作,在发布删除操作之前,我并不总是想删除源。所以我写了我自己的销毁方法来帮助解决这个问题。一切都按照我想要的方式工作,除了 :before_destroy 和 :after_destroy 的自定义回调不再被触发。
关于如何做的任何想法:
- 将回调重新绑定到我的销毁方法
- 使用一些 alias_method_chain 巫术
- 获取模型回调列表,以便我可以手动调用它们
- 用另一种方式解决这个问题
这是我的销毁方法:
def destroy
if self.attribute_names.include?('draft') && self.skip_draft == false
if handle_destroy # if true is returned
super # go ahead and destroy as normal
end
else
super
end
end
更新:我刚刚发现:
correct way to override activerecordbasedestroy,但这似乎提议的技术也不适合回调。有没有办法让我的蛋糕也吃掉?
【问题讨论】:
标签:
ruby-on-rails
activerecord
【解决方案1】:
我错了,当调用 super 时没有调用回调。我最终依赖于我最初发布的确切代码。我改变了我的 handle_destroy 方法的返回方式
我将向您展示我是如何弄清楚在您想要显式触发回调的事件中如何触发回调的。
def destroy
if self.attribute_names.include?('draft') && self.skip_draft == false
if handle_destroy # if true is returned
super # go ahead and destroy as normal
else
# Execute all custom callbacks that are not dependent type callbacks (ie: if the callback method name contains "dependent")
# Dependent callbacks delete records and this is not what the drafting system is all about.
(self.class.before_destroy_callback_chain + self.class.after_destroy_callback_chain).each do |cb|
unless (cb.method.kind_of?(Symbol) && cb.method.to_s.match(/dependent/))
cb.call(self)
end
end
end
else
# normal delete
super
end
end