Rails ActiveRecord: pretty errors when deleting dependent entities with foreign keys constraints
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 stacktra开发者_如何转开发ce 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:
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
精彩评论