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?
source to share
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.
source to share
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.
source to share
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 .
source to share