开发者

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 "W开发者_开发百科ord".

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


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)


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 }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜