gpt4 book ai didi

ruby-on-rails - Ruby on rails,多次检查 nil 属性

转载 作者:行者123 更新时间:2023-12-03 16:10:34 24 4
gpt4 key购买 nike

我正在尝试检查多个属性是否为零,我找到了这篇文章 simplify...但我没有得到我想要的结果。我有一个用户,如果需要,我想更新他们的个人资料。然而,这个用户拥有我想要的所有数据。

  @user.try(:age_id).nil?
#returns false
@user.try(:customer).nil?
#returns false
@user.try(:country).nil?
#returns false

@user.try(:age_id).try(:customer).try(:country).nil?
#returns true

当所有其他尝试的单个实例都以 false 响应时,为什么它在这里以 true 响应?

最佳答案

您正在链接 .try() ,在 try(:age_id) 之后失败:

  • 它试图调用 age_id@user对象
  • 如果 @user.nil? # => 返回 nil
  • 如果 @user.age_id != nil # => 返回 Fixnum
  • 然后你调用方法 try(:customer)在一个明显失败的 Fixnum 上 # => 返回 nil

  • 等等。

    来自 IRB 控制台的示例:
    1.9.3p448 :049 > nil.try(:nothing).try(:whatever).try(:try_this_also).nil?
    => true

    如果要测试所有这些属性都不是 nil,请使用以下命令:
    if @user.present?
    if @user.age_id.presence && @user.customer.presence && @user.country.presence
    # they are all present (!= nil)
    else
    # there is at least one attribute missing
    end
    end

    关于ruby-on-rails - Ruby on rails,多次检查 nil 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20621979/

    24 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com