在Rails应用程序中,有几个表具有外键约束。例如,每个order都属于一个客户。在orders表中有一个costumer_id列。
由于数据库约束,当我删除带有已放置订单的客户时,MySQL将返回错误:
Mysql::Error:无法删除或更新父行:外键约束失败(
orders、约束orders_ibfk_2外键(customer_id)引用customers(id))
和丑陋的错误弹出在屏幕上,所有的堆栈跟踪和那些东西ActiveRecord::StatementIn有效值在DevicesController#destroy .
我想知道是否有一种优雅的方法来处理这些约束错误,给出了一个漂亮的例子,比如“您可以删除这个对象,因为它与X相关联”
我怎么能做到呢?
发布于 2010-02-18 19:36:09
在销毁之前的回调中作出反应:
class Customer < ActiveRecord::Base
before_destroy :no_referenced_orders
has_many :orders
private
def no_referenced_orders
return if orders.empty?
errors.add_to_base("This customer is referenced by order(s): #{orders.map(&:number).to_sentence}")
false # If you return anything else, the callback will not stop the destroy from happening
end
end在主计长中:
class CustomersController < ApplicationController
def destroy
@customer = Customer.find(params[:id])
if @customer.destroy then
redirect_to customers_url
else
render :action => :edit
end
end
endhttps://stackoverflow.com/questions/2290710
复制相似问题