I have a rails 3.2.8 app with the following models: Profile and Report. Profile has many Reports, and of Reports belong to a Profile
If I try to delete_all of the reports for a specific profile:
Profile.first.reports.delete_all
Instead of deleting the reports, it just sets their profile_id to nil using SQL similar to:
UPDATE `reports` SET `profile_id` = NULL WHERE `reports`.`profile_id` = 1 AND `reports`.`id` IN (1, 3)
I can't find anything about this in the guides, is this the correct behaviour? And if not what would cause it?
It's worth noting that using destroy_all works normally, as does using destroy and delete on a singular Report.
Edit (as I can't answer my own question yet):
Changing the relationship of the profile from:
has_many :reports
to:
has_many :reports, dependent: :delete_all
has fixed this, I'm guessing if you don't specify depending, it defaults to :nullify, and calling Profile.first.reports.delete_all doesn't actually delete, it instead does what ever is specified in dependant.
Unless I'm missing something this behaviour is undocumented, but at least it works as I expect now.
If you have defined the association between profile and reports then your code should work else you can try
Report.where(:profile_id => Profile.first.id).delete_all
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