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?
You are chaining the .try()
, which fails after the try(:age_id)
:
age_id
on the @user
object@user.nil?
# => returns nil
@user.age_id != nil
# => returns a Fixnum
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With