ActiveRecord 回调函数列表

39

我已经仔细查看了Rails源代码一段时间,我认为获取所有回调列表的更好方法不存在,除非使用常量列表ActiveRecord::Callbacks::CALLBACKS

也就是说,如果你使用像 devise_invitable 这样的 gem 添加了新的回调 :invitation_accepted,且分数为:after:before,那么ActiveRecord::Callbacks::CALLBACKS将无法正常工作。

除了打开Rails模块并确保每个模型类都有内部回调列表之外,您是否知道其他简单的解决方法?

6个回答

54
你可以通过调用 Model._save_callbacks 来获取保存时的所有回调列表。然后你可以根据自己的需要进行筛选,例如::before 或者 :after,像这样:
Model._save_callbacks.select {|cb| cb.kind == :before}

对于 Model._destroy_callbacks 等内容,工作方式相同。


2
还可以查看文档以获取更详细的信息:http://apidock.com/rails/ActiveRecord/Callbacks - Sam Figueroa

20

文档中提到了"总共有19个回调",但并没有列举这19个回调是什么!

对于那些像我一样谷歌搜索"所有ActiveRecord回调列表"的人,以下是列表(通过使用问题描述中所述的ActiveRecord :: Callbacks :: CALLBACKS找到):

:after_initialize
:after_find
:after_touch
:before_validation
:after_validation
:before_save
:around_save
:after_save
:before_create
:around_create
:after_create
:before_update
:around_update
:after_update
:before_destroy
:around_destroy
:after_destroy
:after_commit
:after_rollback

哦,我刚刚发现它们在指南中列出了这里。尽管如此,我希望这个答案能够为将来的某个人节省一些谷歌时间。 - GMA

3
请注意,如果您只想触发回调函数,可以使用#run_callbacks(kind)方法:
o = Order.find 123 # Created with SQL
o.run_callbacks(:create)
o.run_callbacks(:save)
o.run_callbacks(:commit)

3

如果你在使用._save_callbacks方法之前的Rails版本中工作,可以使用以下方法:

# list of callback_chain methods that return a CallbackChain
Model.methods.select { |m| m.to_s.include? "callback" }.sort

# get all methods in specific call back chain, like after_save
Model.after_save_callback_chain.collect(&:method)

1
我将提供最通用的解决方案。
即使gem声明了自定义回调,例如paranoiaafter_real_destroy,它也可以正常工作。
列出所有回调。
Model.methods.select { |m| m.to_s.include? "callback" }.sort

然后,如果您键入方法名称,例如,您可以获得给定的回调函数。

Model._update_callbacks
Model._real_destroy_callbacks
Model._destroy_callbacks

如果您列出所有回调函数,就可以通过检查@filter实例变量来找到所需的回调函数。
require 'pp'
Activity._destroy_callbacks.each_with_index { |clbk,index| puts "#{index}-------\n#{clbk.pretty_inspect}" } ; nil 

# [...]

#<ActiveSupport::Callbacks::Callback:0x00007ff14ee7a968
 @chain_config=
  {:scope=>[:kind, :name],
   :terminator=>
    #<Proc:0x00007ff13fb825f8@/Users/mypc/.rbenv/versions/2.3.7/lib/ruby/gems/2.3.0/gems/activemodel-4.1.16/lib/active_model/callbacks.rb:103 (lambda)>,
   :skip_after_callbacks_if_terminated=>true},
 @filter=
  #<Proc:0x00007ff14ee7ac10@/Users/mypc/.rbenv/versions/2.3.7/lib/ruby/gems/2.3.0/gems/activerecord-4.1.16/lib/active_record/associations/builder/association.rb:135 (lambda)>,
 @if=[],
 @key=70337193825800,
 @kind=:before,
 @name=:destroy,
 @unless=[]>
4-------
#<ActiveSupport::Callbacks::Callback:0x00007ff14ee3a228
 @chain_config=
  {:scope=>[:kind, :name],
   :terminator=>
    #<Proc:0x00007ff13fb825f8@/Users/mypc/.rbenv/versions/2.3.7/lib/ruby/gems/2.3.0/gems/activemodel-4.1.16/lib/active_model/callbacks.rb:103 (lambda)>,
   :skip_after_callbacks_if_terminated=>true},
 @filter=:audit_destroy,
 @if=[],
 @key=:audit_destroy,
 @kind=:before,
 @name=:destroy,
 @unless=[]>
5-------

0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接