How to destroy an array of objects with one line of code in Ruby on Rails
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 is a web developer for Kyanmedia web agency. He's lucky enough to write in Ruby on Rails full-time and uses this site to post snippets of code.
Contact
my name at gmail.com
More snippets
Take a look in the archive
Need a website?
Contact my employer. Make sure to check out our portfolio of work.
Hosting
I recommend hostingrails.com
1 comment made
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.
Got something to say?