导轨after_save的回调被多次调用 [英] Rails after_save callback being called multiple times

查看:208
本文介绍了导轨after_save的回调被多次调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想通过一个mixin注入的after_save的回调,但我的RSpec的测试告诉我,回调被调用两次当创建方法被调用。为什么被调用的方法两次?

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?

下面RSpec的测试失败

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

这里的code

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

的产品类有其他code,但不具有任何其它的回调。

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

推荐答案

after_save的是交易的一部分,因此也被称为不止一次,只要您有需要保存,以及其他相关的对象。在这样的情况下,我通常将来自after_save的回调至after_commit回调运行于交易完成之后。

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.

这篇关于导轨after_save的回调被多次调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆