我有一个客户模型,它有许多采购订单。在该模型中,在删除客户之前,它会进行检查,以确保该客户没有关联的PO,如果有,则会阻止删除。现在,我在其他型号上使用了几乎完全相同的代码,没有问题,但在这个型号中,如果我试图删除带有PO的客户,我会看到一个白色和红色的屏幕,上面写着在if company.destroy
上引发了ActiveRecord::RecordNotDestroyed错误,而不是重定向到带有漂亮的闪烁警告的客户页面。
型号/公司.rb
class Company < ActiveRecord::Base
belongs_to :user, foreign_key: :account_owner, counter_cache: true
has_many :purchase_orders
before_destroy :po_check
private
def po_check
!self.purchase_orders.any?
end
end
控制器/公司_controller.rb
class CompaniesController < ApplicationController
def destroy
company = Company.find(params[:id])
if company.destroy
flash[:success] = company.name + ' deleted.'
redirect_to companies_path
else
flash[:danger] = 'Cannot delete companies associated with Purchase Orders'
redirect_to company
end
end
end
这可能是Rails版本的问题。Rails 4.1.6说,如果你做你正在做的事情,它会引发这个错误。
您也可以使用:dependent
来实现这一点。示例:
has_many :purchase_orders, dependent: :restrict_with_error
来自文件:
:dependent控制关联对象在所有者被摧毁。请注意,这些是作为回调实现的,并且Rails按顺序执行回调。因此,其他类似的回调可能影响:依赖行为,而:依赖行为可能影响其他回调。
:destroy会导致所有关联的对象也被销毁。
:delete_all将直接删除所有关联的对象从数据库(因此不会执行回调)。
:nullify会将外键设置为NULL。回调不是已执行。
:restrict_with_exception会引发异常,如果存在任何相关记录。
:restrict_with_error会将错误添加到所有者中,如果存在是任何关联的对象。