callback - before_destroy 回调不会阻止记录被删除

标签 callback ruby-on-rails-4

如果有 child ,我正在努力防止记录被破坏。

class Submission < ActiveRecord::Base

has_many :quotations, :dependent => :destroy

 before_destroy :check_for_payments


  def quoted?
    quotations.any?
  end


  def has_payments?
   true if quotations.detect {|q| q.payment}
  end


  private

  def check_for_payments
    if quoted? && has_payments?
      errors[:base] << "cannot delete submission that has already been paid"
      false
    end
  end

end

class Quotation < ActiveRecord::Base

    #associations
    belongs_to :submission
        has_one :payment_notification   
        has_one :payment

         before_destroy :check_for_payments

private 

def check_for_payments
  if payment_notification || payment
    errors[:base] << "cannot delete quotation while payment exist"
    return false
  end
end
end

当我测试此代码时,before_destroy :check_for_ payments 会阻止删除报价记录。

但是,提交 before_destroy 回调中的 :check_for_ payment 并不能阻止提交被删除。

如何阻止付款后的提交内容被销毁?

最佳答案

Rails 5中,您必须抛出:abort,否则它将无法工作。 (甚至返回false)

此外,您应该将 prepend: true 添加到回调中,以确保它在父模型上的 dependent: :destroy 之前运行。

这样的事情应该有效:

class Something < ApplicationRecord

  before_destroy :can_destroy?, prepend: true

  private

  def can_destroy?
    if model.something?
      self.errors.add(:base, "Can't be destroy because of something")
      throw :abort
    end
  end
end

关于callback - before_destroy 回调不会阻止记录被删除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19044725/

相关文章:

Javascript 事件已捕获,但回调函数未执行

ruby-on-rails - rails : change localhost:3000 to https://

ruby-on-rails-4 - 在 ActiveAdmin 中显示 HStore 时出现 Formtastic::UnknownInputError

ruby-on-rails - 使 js.erb 文件在没有 ajax Ruby on Rails 4 的情况下工作

java - JNA回调的使用方法

ios - 从谷歌地图回调到我的应用程序

sql - 使外键也成为 Rails 迁移中的主键

ruby-on-rails - 带助手的 Ruby on Rails 文件夹结构

javascript - 成功后开始下一个功能

Javascript回调函数问题