rukia_kuchiki_21
rukia_kuchiki_21

Reputation: 1329

Check if nested associations has object

I have here a line of code that checks if name column exists in user.identity object. It do not fail if user object has identity. But it fails when user object doesn't have an identity value.

text += "Print me: \n" if @user.identity.name.present? && [email protected]?

I would like to check first if identity exist. How can I do it in a neat way? Is there any method to check chains of nested objects?

I'm trying to avoid long conditions of ifs as much as possible.

Upvotes: 0

Views: 600

Answers (3)

Vrushali Pawar
Vrushali Pawar

Reputation: 3803

You can use it in following way:

text += "Print me: \n" if @user.try(:identity).try(:name) && [email protected](:identity).try(:phone).try(:active?)

Upvotes: 0

RAJ
RAJ

Reputation: 9747

You can use try while calling name like this:

text += "Print me: \n" if @user.identity.try(:name).present? && [email protected](:phone).active?

Note: Because try check lot many other things, try is not preferred in terms of performance, just to avoid checking whether last method can call next or not. You may want to try this (more readable & preferred):

id = @user.identity
text += "Print me: \n" if id && id.name.present? && !id.phone.active? 

Upvotes: 0

Taryn East
Taryn East

Reputation: 27747

yes, you can use try (if you use it once, you have to use it all the way after that)

if @user.try(:identity).try(:name).present?

Upvotes: 1

Related Questions