Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby on rails, multiple check for nil attributes

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?

like image 811
Philip Avatar asked Dec 16 '13 22:12

Philip


1 Answers

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
like image 197
MrYoshiji Avatar answered Nov 07 '22 10:11

MrYoshiji