2010-02-18 63 views
2

我在Rails應用程序中有幾個帶有外鍵約束的表。例如,每個訂單屬於一個客戶。有costumer_id訂單表。Rails ActiveRecord:使用外鍵約束刪除相關實體時出現的錯誤

當我刪除,因爲數據庫約束帶放在順序負荷消費,中,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#摧毀...

我想知道是否有治療這些約束錯誤優雅的方式,給人一種美麗的像「你可以刪除這個對象,因爲它關聯到X」

我該怎麼辦?

回答

3

陣營在之前銷燬回調:

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