An elegant way to only show records if they exist in ERB rails

I find that I use a lot of repetitive code in my ERB views when displaying user information. Along the lines

<% if @user.name.present? %>
  <%= @user.name %>
<% end %>

      

I basically do this for everything in my opinion to avoid bugs (like older users who may not have all new fields).

Is there a better way to do this?

+3


source to share


4 answers


Move the logic to the helper:

def name_for(user)
 user.name if user.name.present?
end

      



And name this helper in your views:

<%= name_for(@user) %>

      

+8


source


Note that calling @user.name

for a user who does not have a name will not result in an error. If it @user.name

was nil

, the error would only occur if you tried to call an additional method on nil

, for example. @user.name.upcase

...

So, if your condition doesn't cover any other part of the view, and you're happy to leave an empty space if the user doesn't have a name, you can just use @user.name

without checking if

.

You can also use try

if you have a more complex example. For example, if users belong to a group, but some older users do not have a group, you can display the group name with:



@user.group.try(:name)

      

try

on nil

just safely returns nil

no error.

+1


source


https://github.com/raganwald/andand

Use this to avoid these mistakes.

user.andand.name

It checks to see if there is a custom object, but does not name its name.

0


source


You can also go to the next one:

<%= @user.name if @user.name.present? %>

      

But if you repeat the same, the best way would be to create a def in your helper, as Florent pointed out .

0


source







All Articles