Check for nil gives error

2019-08-03 03:31发布

问题:

I have this line in my controller:

user = User.any_of({:user_name => login}, {:email => login})

if user.nil?
  # ...
elsif user.legacy_password.nil? 

And it creates this error:

undefined method `legacy_password' for []:Array

Why would this happen? the user object is supposed to be nil. At least that is what the debugger said.

回答1:

I'm assuming your any_of method returns an array of results, not a single result. You probably want to add .first to the end of it, which will give you either a User record, or nil if any_of returned an empty array.

user = User.any_of({:user_name => login},{:email => login}).first


回答2:

Looks like you are using mongoid (#any_of) and it's returning an array.

The error is because you are calling legacy_password on an array, but I assume it is defined on the User model.