【问题标题】:after_destroy callback claims object still existsafter_destroy 回调声明对象仍然存在
【发布时间】:2018-09-11 12:42:14
【问题描述】:

我有一个 after_destroy 回调,我希望它返回 nil 但仍然有一个值。

class WeighIn < ActiveRecord::Base
  belongs_to :check_in
  after_destroy :add_employee_weightloss

  def add_employee_weightloss
    p self.check_in.weigh_in.present? # returns true
  end
end

规格:

it "employee weightloss" do
  ci = CheckIn.create()
  wi = WeighIn.create(check_in_id: ci.id)

  wi.destroy
  expect(wi.reload).to eq(nil) # returns wi instead of nil
end

【问题讨论】:

  • 这会返回什么? record.destroyed?

标签: ruby-on-rails activerecord rspec callback rails-activerecord


【解决方案1】:

您应该改用destroyed?(或exists?,或persisted?),因为present? 只是检查对象是否存在,这是销毁后的正确行为(destroy 本身返回已删除的对象) .

def add_employee_weightloss
  p check_in.weigh_in.destroyed?
end

另外你不应该使用以下内容:

expect(wi.reload).to eq(nil)

因为如果wi 被破坏,您将获得ActiveRecord::RecordNotFound 异常而不是nil。您可以尝试以下方法:

it "employee weightloss" do
  wi = WeighIn.create(check_in: CheckIn.create)
  wi.destroy

  expect(wi.destroyed?).to eq(true)
end

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-10-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多