Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Delete records from table which matches the data in an array?

I have a table of 2 fields. Word and timestamp. Then i have this array which contains some words. How do i delete all the records in the table which match with the words in the array? Suppose that the model is called "Word".

Any ideas on how to achieve this? maybe loop through the array and run some destroy queries. Can anybody direct me here? thanks

like image 513
Maxsy Avatar asked Mar 21 '10 19:03

Maxsy


2 Answers

Do this:

Word.delete_all(:words => words_array)

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

E.g.:

words = ["pop", "pop alternative", "r&b"]
Word.delete_all(:words => words)
like image 169
Harish Shetty Avatar answered Sep 28 '22 18:09

Harish Shetty


If you defined callbacks on the model bare sql won't call them. The recommended way in this case is:

deletable_words = [ 'php', 'c++' ]
objs = Word.find(:all, :conditions => [ "words.word IN (?)",  deletable_words])
objs.each { |o| o.destroy }
like image 21
clyfe Avatar answered Sep 28 '22 20:09

clyfe