Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between restrict_with_exception and restrict_with_error

Tags:

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?

like image 386
Eric Chuhao Chan Avatar asked Jan 03 '18 04:01

Eric Chuhao Chan


2 Answers

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"]}>
like image 110
Mohammad Shahnawaz Avatar answered Oct 19 '22 09:10

Mohammad Shahnawaz


Those are dependent option

What is the dependent option?

The dependent option is an option to decide what to do with child records when deleting a parent record if the model that is Rails has a child record.

restrict_with_exception

:restrict_with_exception – if there are any associated records, an exception will be raised.

:restrict_with_exception - if there are child records, then you ActiveRecord::DeleteRestrictionError will encounter.

restrict_with_error

:restrict_with_error – if there are any associated records, an error will be added to the owner (the record you are trying to delete).

:restrict_with_error - if there is a child record, it can not be deleted, and error information is added to the parent record.

Several Options except those

:destroy - Delete child records with parents.

:delete_all - Delete child records with parents. However, since the record of the DB is deleted directly, the callback processing of the child record is not executed.

:nullify NULL - Update the foreign key of the child record.

You can also google for more

like image 29
fool-dev Avatar answered Oct 19 '22 10:10

fool-dev