开发者

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

开发者 https://www.devze.com 2022-12-23 12:02 出处:网络
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?

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

精彩评论

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

关注公众号