Lighthouse has a new layout. Prefer the old one? Return to the old layout, and switch back any time from the link at the top of each page.

This project is archived and is in readonly mode.

destroy_all with conditions on has_many association

#1300

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%'"

Reported by Justin Smestad · October 30th, 2008 @ 05:33 PM

State: duplicate
Milestone: 2.x
Assigned to: nobody
Importance: none

Activity

  1. David Stevenson
    David Stevenson

    +1... associations should have a destroy_all method if they have a delete_all method.

    November 13th, 2008 @ 11:34 PM

  2. DHH
    DHH
    • 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.

    November 16th, 2008 @ 03:09 PM

  3. Andrew White
    Andrew White

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

    March 25th, 2009 @ 10:46 AM

  4. bingbing