I'm trying to use dependent: :destroy without success.
Lets put a simple example. I create a simple application with the following:
rails g model parent
rails g model child parent:references
Add following lines to parent.rb
has_many :children, dependent: :destroy
I do the following test in rails console (rails c)
p = Parent.create!
c = Child.create!
c.parent = p
c.save
#check association
Child.first == Child.first.parent.children.first
p.delete
#This should return 0
Child.count == 0
And Child.count returns 1.
What I'm missing?
Thanks
what is dependent :destroy. Dependent is an option of Rails collection association declaration to cascade the delete action. The :destroy is to cause the associated object to also be destroyed when its owner is destroyed.
4.2.2.4 :dependent
If you set the :dependent
option to:
:destroy
, when the object is destroyed, #destroy
will be called on its associated objects.:delete
, when the object is destroyed, all its associated objects will be deleted directly from the database without calling their #destroy
method.As per your settings, you have to do p.destroy
.
The :dependent
option can have different values which specify how the deletion is done. For more information, see the documentation for this option on the different specific association types. When no option is given, the behaviour is to do nothing with the associated records when destroying a record.
For has_many
, destroy
and destroy_all
will always call the destroy
method of the record(s) being removed so that callbacks are run. However delete
and delete_all
will either do the deletion according to the strategy specified by the :dependent
option, or if no :dependent
option is given, then it will follow the default strategy. The default strategy is :nullify
(set the foreign keys to nil), except for has_many :through
, where the default strategy is delete_all
(delete the join records, without running their callbacks).
Calling the delete
method on an ActiveRecord derived object will issue a direct DELETE
statement do the database, skipping any ActiveRecord callbacks and configurations such as dependent: destroy
.
I believe you want the destroy
method.
You could also set up a foreign key in the database and set it to cascade on delete, it might make sense, depending on your needs.
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