gpt4 book ai didi

ruby-on-rails - Rails ActiveRecord : pretty errors when deleting dependent entities with foreign keys constraints

转载 作者:行者123 更新时间:2023-12-01 00:03:51 26 4
gpt4 key购买 nike

我在 Rails 应用程序中有几个带有外键约束的表。例如,每 订购 属于客户。有一个 客户_id 上的专栏订单 table 。

当我删除已下订单的客户时,由于数据库限制,MySQL 返回错误:

Mysql::Error: Cannot delete or update a parent row: a foreign key constraint fails (orders, CONSTRAINT orders_ibfk_2 FOREIGN KEY (customer_id) REFERENCES customers (id))



屏幕上弹出难看的错误,包括所有堆栈跟踪和那些东西
ActiveRecord::StatementInvalid 在 DevicesController#destroy ...

我想知道是否有一种优雅的方法来处理这些约束错误,比如“你可以删除这个对象,因为它与 X 相关联”

我怎么能做到?

最佳答案

在销毁之前的回调中使用react:

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

在 Controller 中:
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

关于ruby-on-rails - Rails ActiveRecord : pretty errors when deleting dependent entities with foreign keys constraints,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2290710/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com