问题描述
在销毁一个安静的资源时,我想在允许销毁操作继续之前保证一些事情?基本上,如果我注意到这样做会使数据库处于无效状态,我希望能够停止销毁操作?销毁操作没有验证回调,那么如何验证"销毁操作是否应该被接受?
On destruction of a restful resource, I want to guarantee a few things before I allow a destroy operation to continue? Basically, I want the ability to stop the destroy operation if I note that doing so would place the database in a invalid state? There are no validation callbacks on a destroy operation, so how does one "validate" whether a destroy operation should be accepted?
推荐答案
您可以引发一个异常,然后捕获该异常.Rails 将删除包含在事务中,这有助于解决问题.
You can raise an exception which you then catch. Rails wraps deletes in a transaction, which helps matters.
例如:
class Booking < ActiveRecord::Base
has_many :booking_payments
....
def destroy
raise "Cannot delete booking with payments" unless booking_payments.count == 0
# ... ok, go ahead and destroy
super
end
end
或者,您可以使用 before_destroy 回调.此回调通常用于销毁依赖记录,但您可以抛出异常或添加错误.
Alternatively you can use the before_destroy callback. This callback is normally used to destroy dependent records, but you can throw an exception or add an error instead.
def before_destroy
return true if booking_payments.count == 0
errors.add :base, "Cannot delete booking with payments"
# or errors.add_to_base in Rails 2
false
# Rails 5
throw(:abort)
end
myBooking.destroy
现在将返回 false,并且 myBooking.errors
将在返回时填充.
myBooking.destroy
will now return false, and myBooking.errors
will be populated on return.
这篇关于如何在 Rails 中“验证"销毁的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!