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
, CONSTRAINTorders_ibfk_2
FOREIGN KEY (customer_id
) REFERENCEScustomers
(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?
React in the before destroy callback:
In the controller: