在销毁restful资源时,在允许销毁操作继续之前,我想要保证几件事?基本上,我希望能够停止销毁操作,如果我注意到这样做会将数据库置于无效状态?销毁操作没有验证回调,那么如何“验证”销毁操作是否应该被接受呢?
发布于 2008-09-23 19:22:38
您可以引发一个异常,然后捕获该异常。Rails将删除包装在一个事务中,这有助于解决问题。
例如:
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回调。此回调通常用于销毁依赖记录,但也可以抛出异常或添加错误。
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)
endmyBooking.destroy现在将返回false,并且myBooking.errors将在返回时填充。
发布于 2011-07-29 21:54:27
只需注意:
对于rails 3
class Booking < ActiveRecord::Base
before_destroy :booking_with_payments?
private
def booking_with_payments?
errors.add(:base, "Cannot delete booking with payments") unless booking_payments.count == 0
errors.blank? #return false, to not destroy the element, otherwise, it will delete.
end发布于 2016-06-17 19:36:05
这就是我对Rails 5所做的:
before_destroy do
cannot_delete_with_qrcodes
throw(:abort) if errors.present?
end
def cannot_delete_with_qrcodes
errors.add(:base, 'Cannot delete shop with qrcodes') if qrcodes.any?
endhttps://stackoverflow.com/questions/123078
复制相似问题