【问题标题】:Skip callback on create Rails跳过创建 Rails 的回调
【发布时间】:2016-10-29 00:36:30
【问题描述】:

我想为 Rspec 测试创建一个 Active Record 模型。

但是,这个模型有回调,即:before_create 和 after_create 方法(如果我没记错的话,我认为这些方法称为回调而不是验证)。

有没有办法在不触发回调的情况下创建对象?

我之前尝试过的一些解决方案/不适用于我的情况:

更新方法:

update_column 和其他更新方法不起作用,因为我想创建一个对象,而当对象不存在时我不能使用更新方法。

Factory Girl and After Build:

FactoryGirl.define do
  factory :withdrawal_request, class: 'WithdrawalRequest' do
    ...
    after(:build) { WithdrawalRequest.class.skip_callback(:before_create) }
  end
end

失败/错误:after(:build) { WithdrawalRequest.class.skip_callback(:before_create) }

无方法错误: Class:Class 的未定义方法“skip_callback”

Skip callbacks on Factory Girl and Rspec

跳过回调

WithdrawalRequest.skip_callback(:before_create)

withdrawal_request = WithdrawalRequest.create(withdrawal_params)

WithdrawalRequest.set_callback(:before_create)

失败/错误:WithdrawalRequest.skip_callback(:before_create)

NoMethodError:undefined method `_before_create_callbacks' for #

How to save a model without running callbacks in Rails

我也试过

WithdrawalRequest.skip_callbacks = true

这也不起作用。

--------- 编辑 ------------

我的工厂函数被编辑为:

after(:build) { WithdrawalRequest.skip_callback(:create, :before, :before_create) }

我的 before_create 函数如下所示:

class WithdrawalRequest < ActiveRecord::Base
  ...
  before_create do
    ...
  end
end

--------- 编辑 2 ------------

我将 before_create 更改为一个函数,以便我可以引用它。这些中的任何一个都是更好的做法吗?

class WithdrawalRequest < ActiveRecord::Base
  before_create :before_create
  ...
  def before_create
    ...
  end
end

【问题讨论】:

    标签: ruby-on-rails callback before-filter


    【解决方案1】:

    根据参考答案:

    FactoryGirl.define do
      factory :withdrawal_request, class: 'WithdrawalRequest' do
        ...
        after(:build) { WithdrawalRequest.skip_callback(:create, :before, :callback_to_be_skipped) }
       #you were getting the errors here initially because you were calling the method on Class, the superclass of WithdrawalRequest
    
        #OR
        after(:build) {|withdrawal_request| withdrawal_request.class.skip_callback(:create, :before, :callback_to_be_skipped)}
    
      end
    end
    

    【讨论】:

    • 感谢您的回答。但我仍然有错误(它仍在执行回调)我已经编辑了添加了 before_create do 函数的问题。你知道什么可能导致这个错误吗? (请查看编辑以获取更多信息)
    • 您可以这样做以跳过all 回调吗?对于有很多回调的模型。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-10-11
    • 1970-01-01
    • 2011-11-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多