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
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.