views:

110

answers:

2

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.

When I delete a costumer with a placed order, because of database constraints, MySQL returns the error:

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))

And the ugly error pops up on the screen, with all stacktrace and those stuff ActiveRecord::StatementInvalid in DevicesController#destroy ...

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"

How could I do it?

A: 

React in the before destroy callback:

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

In the 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
François Beausoleil
A: 
enter code here1010101010001011101010101110100111000101010
asd