0

I'm trying to cycle through an array in console and use find_by_email to locate the User:

a = [ "[email protected]",  "[email protected]"]
a.each do |email|
 u = User.find_by_email("#{a}")
 u.delete
end

But I'm getting an error:

NameError: undefined local variable or method `email' for main:Object

Here, what I get based on the answer:

1.9.3p194 :035 > a = [ "[email protected]",  "[email protected]"]
 => ["[email protected]", "[email protected]"] 
1.9.3p194 :036 > a.each do |email|
1.9.3p194 :037 >     u = User.find_by_email(email)
1.9.3p194 :038?>   u.destroy
1.9.3p194 :039?>   end
  User Load (0.7ms)  SELECT "users".* FROM "users" WHERE "users"."email" = '[email protected]' ORDER BY users.created_at DESC LIMIT 1

NoMethodError: undefined method `destroy' for nil:NilClass

1 Answer 1

2

First, don't use #{a}. It refers to the array, use the email variable passed into the loop, which refers to the email of that iteration.

u = User.find_by_email(email)

The reason you are getting the error, is because you are missing do.

a.each do |email|
  u = User.find_by_email(email)
  u.destroy
end

You can optimize the query by writing.

User.where(email: a).destroy_all
Sign up to request clarification or add additional context in comments.

9 Comments

Hi Niels, that gives me: NoMethodError: undefined method `delete' for nil:NilClass. I've pasted the logs in my question.
Yes, the method you are looking for is called destroy.
a = [ "[email protected]", "[email protected]"] a.each do |email| u = User.find_by_email(email) u.destroy end NoMethodError: undefined method `destroy' for nil:NilClass
In that case, you don't have any users with those e-mail addresses.
Try User.where(email: a).count
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.