Ruby check if record exists and associations in one line

Viewed 332

Something I always run in to. I want to do this:

if current_user.exists? && current_user.role == "admin"
  # Do something
end

Obviously if current user does not exist then this does not work as it returns undefined method role for nil class

Is there a way I can achieve the above in one line without multiple If statements?

2 Answers

You can use traditional .try

current_user.try(:role) == "admin"

or safe navigation operator for which is faster &. if you're using ruby >= 2.3.0

current_user&.role == "admin"

Related