代码之家  ›  专栏  ›  技术社区  ›  Daniel Cukier

Rails ActiveRecord:删除具有外键约束的依赖实体时出现错误

  •  3
  • Daniel Cukier  · 技术社区  · 16 年前

    我在Rails应用程序中有几个带有外键约束的表。例如,每个 秩序 属于客户。有一个 肋骨化石 列上 命令 表。

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

    MySQL::错误:无法删除或更新 父行:外键约束 失败(失败) orders 约束 orders_ibfk_2 外键 ( customer_id 参考文献 customers ( id )

    屏幕上会弹出一个丑陋的错误,包括所有的stacktrace和那些东西。 ActiveRecord::StatementInvalid in DeviceSController Destroy…

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

    我怎么能做到?

    1 回复  |  直到 16 年前
        1
  •  4
  •   François Beausoleil    16 年前

    在销毁前回调中做出反应:

    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