我的自定义destroy方法不会在destroy回调之前和之后触发默认值

时间:2009-12-21 20:21:35

标签: ruby-on-rails activerecord

我正在编写一个插件,为模型提供绘图。删除操作是一个可以起草的操作,在发布删除之前,我并不总是希望删除原始操作。所以我编写了自己的destroy方法来帮助解决这个问题。除了:before_destroy:after_destroy的自定义回调不再被触发之外,所有内容都完全符合我的要求。

关于如何:

的任何想法
  1. 将回调重新绑定到我的销毁方法
  2. 使用alias_method_chain voodoo
  3. 获取模型回调列表,以便我可以将其称为手动
  4. 以另一种方式解决这个问题
  5. 这是我的破坏方法:

      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,但似乎提议的技术也不适合回调。有没有办法吃我的蛋糕并吃它?

1 个答案:

答案 0 :(得分:0)

我在调用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