What is the correct way to refer to current_user.user_profile.name when there may or may not be a user_profile record for a particular user?
I have two tables, User (:email) and UserProfile (:name, :company).
User has_one user_profile, and UserProfile belongs_to User
A profile may or may not not exist. (It’s optional for users)
In lot of my code and views I want to display the user’s name and company, for example current_user.user_profile.name
Of course, if the user has not created their profile yet, current_user.user_profile is nil, so referencing current_user.user_profile.name throws an error.
I know how to do it the wrong way (check for nil before referencing the .name field EVERY time I need the name).
The best I can think of is create a User method called name that does the nil checking so current_user.name returns the name (or “” if there is no profile). But that feels wrong, too, since I have to write a method for every single field I add to user_profile.
You could do something like this that should work with all attributes of the
UserProfile:Then you’d just call
Edit
Dylan’s
trymethod also works: