This project is archived and is in readonly mode.
destroy_all with conditions on has_many association
Reported by Justin Smestad | October 30th, 2008 @ 05:33 PM | in 2.x
Added HasManyAssociation#destroy_all with conditions to has_many association in order to skip calling find explicitly and then destroy on each of those in the result set. All this is done while preserving the original ActiveRecord::Base.destroy_all functionality when no conditions are passed.
Changes this: @post.comments.find(:all, :conditions => "name LIKE 'stupid%'").each {|record| record.destroy }
To: @post.comments.destroy_all "name LIKE 'stupid%'"
Comments and changes to this ticket
-
David Stevenson November 13th, 2008 @ 11:34 PM
+1... associations should have a destroy_all method if they have a delete_all method.
-
DHH November 16th, 2008 @ 03:09 PM
- State changed from new to duplicate
This is already possible with the destroy_all on AssociationCollection. Your example would be @post.comments.all(:conditions => "name LIKE 'stupid%'").destroy_all.
-
Andrew White March 25th, 2009 @ 10:46 AM
Just want to add to this two comments as my first instinct when needing to restrict a destroy_all was to pass conditions in.
Firstly the example provided by DHH is incorrect - you need to use
scoped
rather thanall
. Secondly, while using scoped works I'd like to see consistency between the collection methods and AR::Base methods - so delete and destroy should accept ids and delete_all and destroy_all should accept conditions.
Create your profile
Help contribute to this project by taking a few moments to create your personal profile. Create your profile »
<h2 style="font-size: 14px">Tickets have moved to Github</h2>
The new ticket tracker is available at <a href="https://github.com/rails/rails/issues">https://github.com/rails/rails/issues</a>