Avoid printing attributes of the nil object in Rails Currently, when I'm wanting to print a value for my class I do the following...

&lt;%= @person.team.name if @person.team.present? %&gt;


This seems really redundant to me.  I've also have done...

&lt;%= @person.team.name_display %&gt;


where I've created a function for each attribute to kind of hide the first case.  It seems a little much though. Is there a more preferred way to do it such as...

&lt;%= @person.team.name || "" %&gt;
You are right, you code is too verbose. This is a pretty common pattern and you have some alternatives. For example, active_support has the abstraction Object#try:

&lt;%= @person.team.try(:name) %&gt;


Another alternative is the Object#maybe proxy: https://github.com/bhb/maybe

&lt;%= @person.team.maybe.name %&gt;