Question

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

Was it helpful?

Solution

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 }

OTHER TIPS

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)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top