检查nil给出错误

我的控制器中有这一行:

user = User.any_of({:user_name => login}, {:email => login}) if user.nil? # ... elsif user.legacy_password.nil? 

它会产生这个错误:

 undefined method `legacy_password' for []:Array 

为什么会这样? 用户对象应该是nil 。 至少这是调试器所说的。

我假设你的any_of方法返回一个结果数组,而不是一个结果。 您可能希望将.first添加到它的末尾,这将为您提供用户记录,如果any_of返回空数组, any_of nil

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

看起来你正在使用mongoid( #any_of )并且它正在返回一个数组。

该错误是因为您在数组上调用legacy_password ,但我认为它是在User模型上定义的。