Delete records from the table that match the data in the array?

I have a table of 2 fields. Word and time stamp. Then I have this array that contains a few words. How to delete all records in the table that match the words in the array? Suppose the model is called "Word."

Any ideas on how to achieve this? perhaps loop through the array and run some destruction requests. Can someone direct me here? thanks

+7
ruby ruby-on-rails rails-activerecord
source share
2 answers

If you defined callbacks on the model, then bare sql will not call them. Recommended method in this case:

deletable_words = [ 'php', 'c++' ] objs = Word.find(:all, :conditions => [ "words.word IN (?)", deletable_words]) objs.each { |o| o.destroy } 
+4
source share

Do it:

 Word.delete_all(:words => words_array) 

This will delete the rows matching the words in the specified array in the ONE SQL statement.

eg:.

 words = ["pop", "pop alternative", "r&b"] Word.delete_all(:words => words) 
+18
source share

All Articles