在下面的代码中,返回的用户对象不是nil,但并非所有成员都有其相关值,例如。
用户ID:18,提供者:nil,uid:nil,名称:“newonenewone”,oauth_token:nil,oauth_expires_at:nil,created_at:“2013-12-28 22:17:35“,updated_at:”2013-12-28 22:17:35“,电子邮件: “newonenewone@newonenewone.com”,encrypted_password: “14972b4 ...”
但是当检查用户对象是否为nil时,它返回true!那么为什么会发生这种情况以及如何解决它。
def self.authenticate(email, submitted_password)
user = find_by_email(email)
return nil if user.nil?
return user if user.has_password?(submitted_password)
end
答案 0 :(得分:2)
如果用户不是nil
但,则用户没有密码时,请仔细阅读您的代码。在这种情况下,authenticate
方法将返回nil
。发生这种情况是因为在第二个return
语句之后您没有处理任何情况。这导致Ruby约定nil
返回。
换句话说,您可能希望在下面添加代码:
def self.authenticate(email, submitted_password)
user = find_by_email(email)
return nil if user.nil?
return user if user.has_password?(submitted_password)
# TODO: handle case when !user.nil? && !user.has_password?
end