Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Running destroy_all on an array?

How can I run destroy_all on an array?

I've got the follow query:

spam_users = User.find_by_sql("SELECT * FROM users WHERE email ~* '21cn.com'")

I've tried running spam_users.destroy_all but I get undefined method 'destroy_all' for #<Array:0x10b09ce30>.

I'm running Rails 2.3.8 in this particular app along with PostgreSQL.

like image 686
Shpigford Avatar asked Sep 12 '11 03:09

Shpigford


1 Answers

You don't execute destroy_all on an array, destroy_all is a class method on your models. The following should kill off everything would be in your spam_users array:

User.destroy_all("email ~* '21cn.com'")

You could also iterate over spam_users and destroy them one by one if you already had them for other purposes:

spam_users.each(&:destroy)

You might want to adjust your regex a bit as well:

User.destroy_all("email ~* '21cn\\.com$'")

so that you're looking for a literal . rather than "any character" and anchor it to the end of the string. You could also use a %q(...) quoted string to reduce the escaping:

User.destroy_all(%q(email ~* '21cn\.com$'))
like image 76
mu is too short Avatar answered Sep 28 '22 01:09

mu is too short