如果有 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/