删除与外键约束依赖实体时pretty的错误:Rails的ActiveRecord的 [英] Rails ActiveRecord: pretty errors when deleting dependent entities with foreign keys constraints
问题描述
我在与外键约束的Rails应用程序几个表。例如,每个为了属于客户。有一个 costumer_id 的订单表列。
I have in Rails application several tables with foreign keys constraints. For example, every order belongs to a customer. There's a costumer_id column on the orders table.
当我删除,因为数据库约束的负荷消费与摆放顺序,MySQL返回错误:
When I delete a costumer with a placed order, because of database constraints, MySQL returns the error:
Mysql的::错误:无法删除或更新
父行,外键约束
失败(订单
,约束
orders_ibfk_2
外部关键字
( CUSTOMER_ID
)参考客户
( ID
))
Mysql::Error: Cannot delete or update a parent row: a foreign key constraint fails (
orders
, CONSTRAINTorders_ibfk_2
FOREIGN KEY (customer_id
) REFERENCEScustomers
(id
))
和丑陋的错误弹出在屏幕上,所有的堆栈跟踪那些东西 ActiveRecord的:: StatementInvalid在DevicesController#摧毁...
And the ugly error pops up on the screen, with all stacktrace and those stuff ActiveRecord::StatementInvalid in DevicesController#destroy ...
我想知道是否有一个优雅的方式来对待这些约束错误,给人一种美丽的像你可以删除此对象,因为它关联到X
I'd like to know if there's an elegant way to treat these constraint errors, giving a beautiful like "you can delete this object because it is associated to X"
我怎么能这样做呢?
推荐答案
阵营中的前销毁回调:
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
end
这篇关于删除与外键约束依赖实体时pretty的错误:Rails的ActiveRecord的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!