之前我的自定义销毁方法不会触发违约和破坏后回调 [英] My custom destroy method does not trigger the default before and after destroy callbacks

查看:272
本文介绍了之前我的自定义销毁方法不会触发违约和破坏后回调的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写一个插件,它提供起草车型。删除操作是draftable行动,我并不总是想要删除的起源,直到删除发布。所以,我写我自己破坏的方法来帮助了这一点。一切工作完全按照我想要的东西除外,自定义回调:before_destroy :after_destroy 不再被触发。

I am writing a plugin that provides drafting for models. A delete action is a draftable action and I do not always want to delete the origin until that deletion is published. So I wrote my own destroy method to help out with this. Everything works exactly as I want things to except, custom callbacks for :before_destroy and :after_destroy are no longer being triggered.

在任何想法如何:

  1. 重新绑定回调到我的destroy方法
  2. 工作的一些alias_method_chain巫术
  3. 在领型的回调列表,以便我可以给他们打电话手动
  4. 在解决这个问题的另一种方法

下面是我破坏方法:

  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

更新:我刚刚发现这一点: 覆盖activerecordbasedestroy 正确的方法,但这似乎是所提出的技术并不适应的试镜。有没有办法让我的鱼和熊掌兼得呢?

Update: I just found this: correct way to override activerecordbasedestroy, but that seems like the proposed technique does not accomodate for callbacks either. Is there a way to have my cake and eat it too?

推荐答案

我错了没有被调用时超被称为回调。我结束了依靠精确的code我最初张贴。我改变了我的handle_destroy方法返回

I was wrong about the callbacks not being called when super is called. I ended up relying on the exact code I initially posted. I changed how my handle_destroy method returned

我会告诉你我是怎么想通了这如何可能触发回调中要明确触发回调的情况。

I'll show you how I figured out how it is possible to fire the callbacks in the event you want to explicitly fire the callbacks.

  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

这篇关于之前我的自定义销毁方法不会触发违约和破坏后回调的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆