Reputation: 9647
I am trying to write this code in more elegant way in my view. Can you help me?
<%= if category.photo.present?
category.photo
else
category.img_parse_url
end %>
category.photo
might be nil or empty string)
Upvotes: 0
Views: 27
Reputation: 7869
You can use try method which is not needed here as @tadman pointed out, besides, as you wrote below in comment photo
can be an empty string (I wrongly assumed it cannot be) so those two versions will return an empty string if category.photo
is just an empty string:
<= category.try(:photo) || category.img_parse_url %>
And without try
:
<= category.photo || category.img_parse_url %>
or move that to model.
edit:
If the photo can be an empty string then maybe use ternary operator?
<%= category.photo.present? ? category.photo : category.img_parse_url %>
or use the presence method:
<%= category.photo.presence || category.img_parse_url %>
Upvotes: 1