Rails after_save回调被多次调用

Bri*_*ick 10 activerecord ruby-on-rails ruby-on-rails-3

我试图通过mixin注入一个after_save回调,但是我的rspec测试告诉我在调用该create方法时调用了两次回调.为什么方法被调用两次?

以下rspec测试失败

it 'should call callback' do
  Product.any_instance.should_receive(:update_linkable_attachments).once
  Product.create(:name=>'abc')
end
Run Code Online (Sandbox Code Playgroud)

失败消息是:

Failure/Error: Unable to find matching line from backtrace
   (#<Product:0xb7db738>).update_linkable_attachments(any args)
       expected: 1 time
       received: 2 times
Run Code Online (Sandbox Code Playgroud)

这是代码

module MainModuleSupport
  def self.included(base)
    base.instance_eval("after_save :update_linkable_attachments")
  end 

  def update_linkable_attachments
    LinkedAttachment.delay.create_from_attachment self
  end
end

class Product < ActiveRecord::Base
  include MainModuleSupport
  ...

end
Run Code Online (Sandbox Code Playgroud)

Product类有其他代码,但没有任何其他回调.

hea*_*xer 7

after_save是事务的一部分,因此可以多次调用,前提是您还有其他需要保存的关联对象.在这种情况下,我通常会从after_save回调转移到after_commit回调,该回调仅在事务完成后运行.

  • 这是一个很好的建议,但如果我想确保所有操作(save和回调操作)作为单个事务的一部分一起提交,该怎么办? (5认同)