How to destroy an array of objects with one line of code in Ruby on Rails

Posted on 26 September 2007

The easiest way is to collect all the id's of the objects you want to delete and then use the destroy method on the model of those objects.

Model.destroy @user.things.collect(&:id)

The collect method with the &: syntax is the same as doing:

@user.things.collect {|thing| thing.id}

It just creates an array of id's.

And rather than looping through the objects with an each loop and deleting each one in turn, I prefer using the destroy method because it creates a single SQL query rather than one for each object.

About Paul

Paul works for Kyan web design agency in Surrey, UK as a Ruby on Rails developer.

Follow Paul on Twitter

Email: paulsturgess [at] gmail.com

Read more articles in the archive →

Comments...

  • To get an array of ids for associated objects you can also do @user.thing_ids (note that its thing not things)
    However this only works with has_many and has_and_belongs_to_many relationships but not with has_many :through relationships.

    Ahsan at 29 Sep 07 at 09:13

  • Thanks for noting the SQL performance tip.

    Michael L at 21 Sep 10 at 17:30

  • Pretty cute line. Thx :-)

    Picard at 20 Dec 10 at 09:11

  • Thank you. This works perfectly but it could be lighter like that :

    Model.destroy @user.things

    Perhaps because of Rails 3. I don't know but it works.

    Alex at 10 Feb 11 at 01:24

  • I Think should be better one

     @user.things.destroy_all 

    nethin stany dsouza at 05 Oct 11 at 03:54

Got something to say?