Rails after_save callback being called multiple times

帅比萌擦擦* 提交于 2019-12-10 12:53:42

问题


I'm trying to inject an after_save callback via a mixin, but my rspec tests are telling me that the callback is being called twice when the create method is called. Why is the method being called twice?

The following rspec test fails

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

The failure message is:

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

Here's the code

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

The Product class has other code, but does not have any other callbacks.


回答1:


after_save is part of the transaction and therefore may be called more than once provided that you have other associated objects that need to be saved as well. In cases like this I typically move from the after_save callback to the after_commit callback which runs only after the transaction has completed.



来源:https://stackoverflow.com/questions/7603448/rails-after-save-callback-being-called-multiple-times

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!