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.

Comments left...

  • 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

Got something to say?