如何区分是哪个回调运行rails

How to distinguish the which callback run rails

我在两个回调 before_destroybefore_update 中使用相同的方法。在方法内部如何检查哪个回调调用了这个方法?

我的回电:

before_destroy :set_manager_to_true_of_any_trainee
before_update :set_manager_to_true_of_any_trainee

这是我的回调方法:

def set_manager_to_true_of_any_trainee
  if destroy_callback
     # code here
  else
     # code here
  end
end

我这样做是因为 90% 的代码对于两个回调都是相同的,但是对于 before_destroy 我需要跳过一个条件。

在此先致谢。

我可以建议你分开吗?

class YourModel

  before_destroy :on_destroy_set_manager_to_true_of_any_trainee
  before_update :on_update_set_manager_to_true_of_any_trainee

  def on_destroy_set_manager_to_true_of_any_trainee
    set_manager_to_true_of_any_trainee(true)
  end

  def on_update_set_manager_to_true_of_any_trainee
    set_manager_to_true_of_any_trainee
  end

  private

  def set_manager_to_true_of_any_trainee(destroying=false)
  end

end

我们可以找到这笔交易属于哪个动作

看这个方法transaction_include_action?

但是您找不到它是哪个回调,即 after_createbefore_create 但它确保此交易属于 create 操作。

在您的情况下,可以按如下方式使用,

if transaction_include_action?(:update)
...
else transaction_include_action?(:destroy)
...
end

注意:- 此方法在 Rails4 中已弃用。新方法引入了 transaction_include_any_action?(actions) ,它接受一系列操作。参见 here

祝一切顺利!