Difference between restrict_with_exception and restrict_with_error

Eric Chuhao Chan picture Eric Chuhao Chan · Jan 3, 2018 · Viewed 7k times · Source

Can anyone tell me the difference between these two ways when dealing with object whose parent key is destroyed? What practical reason makes you choose one from the other?

Answer

Mohammad Shahnawaz picture Mohammad Shahnawaz · Jan 3, 2018

restrict_with_exception

If there are any associated records, an exception will be raised with:

class Student< ActiveRecord::Base
  has_many :courses, dependent: :restrict_with_exception
  has_many :books
end

restrict_with_error

If there are any associated records, an error will be added to the owner (the record you are trying to delete) with:

class Foo < ActiveRecord::Base
  has_many :bars, dependent: :restrict_with_error
end

Expected behavior

For standard validations the error messages contain the translations and the error details contain the keys, as here with a blank error:

f1 = Foo.new
f1.save!
#=> ActiveRecord::RecordInvalid: Validation failed: Name can't be blank
f1.errors
#=> #<ActiveModel::Errors:0x007fb666637af8
#=> @base=#<Foo:0x007fb6666ddbb0 id: nil, name: nil>,
#=> @details={:name=>[{:error=>:blank}], :type=>[{:error=>:blank}]},
#=> @messages={:name=>["can't be blank"], :type=>["can't be blank"]}>