开发者

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, CONSTRAINT orders_ibfk_2 FOREIGN KEY (customer_id) REFERENCES customers (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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜