检查无错误 [英] Check for nil gives error

查看:71
本文介绍了检查无错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的控制器中有以下行:

I have this line in my controller:

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

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

它会产生此错误:

undefined method `legacy_password' for []:Array

为什么发生这种情况吗?该用户对象应该为 nil

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

推荐答案

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

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

这篇关于检查无错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆