Rails: Restrict with error or exception

为了阻止已关联的记录被删除,ActiveRecord提供了restrict_with_exceptionrestrict_with_error这两种方式。

restrict_with_exception

class Company < ActiveRecord::Base
  has_many :works, dependent: :restrict_with_exception
end

Company.first.destroy # => ActiveRecord::RecordNotDestroyed: Failed to destroy the record

ROLLBACK并抛出异常,终止后续的程序执行

restrict_with_error

class Company < ActiveRecord::Base
  has_many :works, dependent: :restrict_with_error
end

company = Company.first
company.destroy
# ROLLBACK
company.errors # => ...@messages={:base=>["由于 works 需要此记录,所以无法移除记录"]}...

ROLLBACK把错误信息errors添加到调用的对象上

Reference:

Difference between restrict_with_exception and restrict_with_error