Rails ActiveRecord: pretty errors when deleting de

2019-05-09 22:44发布

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?

1条回答
啃猪蹄的小仙女
2楼-- · 2019-05-09 23:10

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
查看更多
登录 后发表回答