无法删除或更新父行外键约束失败 rails

cannot delete or update a parent row a foreign key constraint fails rails

我在尝试删除 rails 中的值时收到以下错误消息“无法删除或更新父行,外键约束失败 rails

这对我来说是完全可以接受的,因为我不希望用户能够删除与另一个值相关联的值。但是,捕获异常然后通知 'alert' 用户不能删除该值的最佳方法是什么?

谢谢,

台湾

*********** Mysql Error:
"Cannot delete or update a parent row: a foreign key constraint fails."

此错误消息通常由数据库 (mysql) 而不是 rails(活动记录) 引发,并且通常会包含在活动记录异常中,例如 ActiveRecord::RecordNotUnique

尝试以下操作找出要捕获的异常:

begin
   <delete action expected to raise the above mentioned error>
rescue Exception => e
  logger.debug "#{e.class}"
end

有很多方法可以优雅地处理这个问题。如果您想在销毁前进行检查,我建议您看看这个 post as it shows a good example of using the before_destroy method and gives you control of the error you show. However, you can also add a rescue_from and capture the error in your controller.