【问题标题】:Rails after_save callback being called multiple timesRails after_save 回调被多次调用
【发布时间】:2011-11-28 00:59:53
【问题描述】:

我正在尝试通过 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

失败信息是:

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

这是代码

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

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

【问题讨论】:

  • Rails 版本?我认为这在几个版本中存在问题。
  • LinkedAttachment 可能会在创建时触发此问题,如果它与产品以某种方式相关
  • 我创建了一个干净的 Rails 应用程序 3.0.10。它在那里工作正常。你能告诉我LinkedAttachment.delay.create_from_attachment是什么吗?

标签: ruby-on-rails ruby-on-rails-3 activerecord


【解决方案1】:

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

【讨论】:

  • 这是一个很好的建议,但是如果我想确保所有操作(保存和回调操作)作为单个事务的一部分一起提交呢?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多