【问题标题】:nil? method returns true even if the object is not nil零?即使对象不是 nil,方法也返回 true
【发布时间】:2013-12-28 23:32:04
【问题描述】:

在下面的代码中,返回的用户对象不是 nil,但并非所有成员都有其相关值,例如

用户 id: 18, 提供者: nil, uid: nil, name: "newonenewone", oauth_token: nil, oauth_expires_at: nil, created_at: "2013-12-28 22:17:35”,更新时间:“2013-12-28 22:17:35”,电子邮件: “newonenewone@newonenewone.com”,加密密码: “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

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-4


    【解决方案1】:

    如果用户不是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
    

    【讨论】:

    • 我认为这可以处理(user && user.has_password?(submitted_pa​​ssword))?用户:无
    • 是的,这将完全等同于您所拥有的。即它的行为相同,当提交的密码不匹配时仍然返回nil
    • OPS,我误解了这一点。如果密码为 nil,则不会调用 authenticate 方法我添加了这一行 return user if !user.nil? && !user.has_password?(submitted_pa​​ssword) 但即使密码不匹配也会使方法返回用户,所以我在这里仍然有麻烦。
    • 我没有关注你。请发布您的新代码以及使其失败所需的用例。
    猜你喜欢
    • 2020-04-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-24
    • 1970-01-01
    • 2014-09-26
    • 1970-01-01
    相关资源
    最近更新 更多