Rails ActiveRecord: pretty errors when deleting dependent objects with foreign key constraints

I have several tables with foreign key restrictions in my Rails application. For example, each order belongs to the customer. There is a costumer_id column in the order table .

When I delete a client with a placed order, due to database restrictions, MySQL returns an error:

Mysql :: Error: unable to delete or update parent line: foreign key constraint failed ( orders, CONSTRAINT orders_ibfk_2FOREIGN KEY ( customer_id) LINKS customers( id))

And an ugly error appears on the screen, with all the stacktrace and those ActiveRecord :: StatementInvalid things in DevicesController # destroy ...

I would like to know if there is an elegant way to handle these constraint errors, giving a beautiful look "you can delete this object because it is associated with X"

How can i do this?

+2
source share
1 answer

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
+3
source

Source: https://habr.com/ru/post/1570022/


All Articles