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?
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"]}>
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With