ActiveRecord delete_all method updating instead of deleting
activerecord, rails-activerecord, ruby-on-rails, ruby-on-rails-4.1
Solution
From the Rails API docs for `delete_all`:
Deletes all the records from the collection. For has_many associations, the deletion is done according to the strategy specified by the :dependent option. Returns an array with the deleted records.
If no :dependent option is given, then it will follow the default strategy. The default strategy is :nullify. This sets the foreign keys to NULL. For, has_many :through, the default strategy is delete_all.
So you you just need to set the `:dependent` option on your `has_many` to either `:delete_all` or `:destroy`, depending on what behavior you want.
has_many :cash_histories, as: :cashable, dependent: :delete_all
From the Rails API docs for `has_many`:
Objects will be in addition destroyed if they're associated with dependent: :destroy, and deleted if they're associated with dependent: :delete_all.
Problem
I'm using Rails polymorphic associations, that way some models have many `cash_histories` children, like this: ``` has_many :cash_histories, as: :cashable ``` But when I try to delete all cash histories from a parent `@resource`, like this: ``` @resource.cash_histories.delete_all ``` I get the following query: ``` UPDATE "cash_histories" SET "cashable_id" = NULL WHERE "cash_histories"."cashable_id" = $1 AND "cash_histories"."cashable_type" = $2 [["cashable_id", 1], ["cashable_type", "ServiceOrder"]] ``` I can't understand this behavior, setting relationship id to null instead of removing, that will result in dead rows in my table. Why is that happening? I'm using Rails 4.1.