7

I'm trying to check multiple attributes for nil, I've found this post simplify... but I'm not getting the results I want. I have a user whom I want to update their profile if needed. This user however has all the data I want.

  @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

Why is it responding with true here when all the other single instances of tries responds with false?

Community
  • 1
  • 1
Philip
  • 6,827
  • 13
  • 75
  • 104

1 Answers1

9

You are chaining the .try(), which fails after the try(:age_id):

  • It tries to call age_id on the @user object
  • if @user.nil? # => returns nil
  • if @user.age_id != nil # => returns a Fixnum
  • Then you call the method try(:customer) on a Fixnum which obviously fails # => returns nil

etc.

An example from the IRB console:

1.9.3p448 :049 > nil.try(:nothing).try(:whatever).try(:try_this_also).nil?
 => true 

If you want to test that all of these attributes are not nil, use this:

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
MrYoshiji
  • 54,334
  • 13
  • 124
  • 117