dependent destroy not working

ruby-on-rails, ruby-on-rails-4

Solution

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

Problem

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

Original source