Rails 4.2.6:
我有一个after_commit
,它被定义为仅通过传递on: :create
选项在创建时执行。
在测试中,我使用skip_callback
和set_callback
来绕过此执行。但是,由于我无法弄清楚如何提供set_callback
选项,因此我无法正确使用on: :create
。
我一直在阅读文档,但没有运气!
after_commit :create_report, on: :create
Order.skip_callback(:commit, :after, :create_report)
Order.set_callback(:commit, :after, :create_report)
答案 0 :(得分:1)
我也遇到了这个问题。我能够通过修改原始类的猴子来解决。在您的情况下,可能应该这样做:
# disable your callbacks
Order.skip_callback(:commit, :after, :create_report)
# do whatever you need to do...
# Restore callbacks with monkey patch
class Order ; after_commit :create_report, on: :create ; end
请继续阅读以下详细信息:
通过查看__callbacks
,我可以弄清楚这一点:
最初定义时,如下所示:
:commit=>
#<ActiveSupport::Callbacks::CallbackChain:0x00007fbd0aceaf80
@callbacks=
#<ActiveSupport::Callbacks::CallbackSequence:0x00007fbd4a2f18b8
@after=
[#<Proc:0x00007fbd4a2f0df0@/Users/ryanjodonnell/.rvm/gems/ruby-2.6.5/gems/activesupport-5.2.4.2/lib/active_support/callbacks.rb:256>],
@before=[],
@call_template=nil,
@nested=nil,
@user_conditions=nil>,
@chain=
[#<ActiveSupport::Callbacks::Callback:0x00007fbd0aceb200
@chain_config=
{:scope=>[:kind, :name],
:terminator=>
#<Proc:0x00007fbd480e0670@/Users/ryanjodonnell/.rvm/gems/ruby-2.6.5/gems/activesupport-5.2.4.2/lib/active_support/callbacks.rb:603>},
@filter=:create_report,
@if=
[#<Proc:0x00007fbd0aceb5c0@/Users/ryanjodonnell/.rvm/gems/ruby-2.6.5/gems/activerecord-5.2.4.2/lib/active_record/transactions.rb:288 (lambda)>],
@key=:create_report,
@kind=:after,
@name=:commit,
@unless=[]>],
使用Order.skip_callback(:commit, :after, :create_report)
禁用回调后,请注意您的回调现在按预期丢失:
:commit=>
#<ActiveSupport::Callbacks::CallbackChain:0x00007fbd0b672ad0
@callbacks=nil,
@chain=[],
@config=
{:scope=>[:kind, :name],
:terminator=>
#<Proc:0x00007fbd480e0670@/Users/ryanjodonnell/.rvm/gems/ruby-2.6.5/gems/activesupport-5.2.4.2/lib/active_support/callbacks.rb:603>},
@mutex=#<Thread::Mutex:0x00007fbd0b672a80>,
@name=:commit>,
现在,使用Order.set_callback(:commit, :after, :create_report)
重新创建回调,您将注意到回调已恢复,但缺少@if=[#Proc]
:commit=>
#<ActiveSupport::Callbacks::CallbackChain:0x00007fbd0ae90790
@callbacks=nil,
@chain=
[#<ActiveSupport::Callbacks::Callback:0x00007fbd0ae90998
@chain_config=
{:scope=>[:kind, :name],
:terminator=>
#<Proc:0x00007fbd480e0670@/Users/ryanjodonnell/.rvm/gems/ruby-2.6.5/gems/activesupport-5.2.4.2/lib/active_support/callbacks.rb:603>},
@filter=:create_report,
@if=[],
@key=:create_report,
@kind=:after,
@name=:commit,
@unless=[]>],
答案 1 :(得分:0)
来自after_commit文档:
请注意,事务性灯具无法很好地使用此功能。请使用test_after_commit gem在测试中触发这些钩子。