I am new to rails and was wondering if it were possible to have a default message in the view if the database entry was empty. For example if you had an image you could do this:
<%= image_tag "#{post.imge}", :alt => 'Currently no image available'%>
So if there wasn't an image link in there it would come up with "Currently no image available" But say if you just wanted to show a string so:
<%= post.info %>
But if post.info were empty I want display an alternative message like "Currently no information available"? I know that <%= post.info, :alt => 'Currently no information available'%> doesn't work but I can't seem to find any way to do this - probably because it is so easy no one has ever asked the question lol!
I am trying to use the solution below in a helper since I want to use for a few different entries but I can't seem to get it to work - I have added my code below:
module ApplicationHelper
def chk_blnk(gogo)
if gogo.blank?
"No img"
else
return gogo
end
end
end
I'm also not sure how to call it in the view when it takes in a variable (post.info) I know that usually you would call it as such:
<%= chk_blnk %>
I'm sorry if these are really basic questions I have tried searching for answers but again I can't seem to find any.
You could do this:
<%= post.info.blank?? 'No post' : post.info %>
or, if you know that post.info will be nil (rather than an empty string) when there isn't anything in it:
<%= post.info || 'No Post' %>
or, if you need to include some markup:
<% if post.info.blank? %>
<p>No Post</p>
<% else %>
<%= post.info %>
<% end %>
BTW, the behavior of this:
<%= image_tag "#{post.imge}", :alt => 'Currently no image available' %>
when there is no image to display is browser dependent: some will give you a broken image icon, some will display the alt text, some will display nothing. You are abusing the alt attribute:
The preferred means for marking up a text alternative for an
imgelement is to use thealtattribute to provide a full equivalent for the image, or to provide analtattribute with an empty value (to indicate that the image is purely presentational).
The alt text is supposed to be a description of the image suitable for screen readers and other non-graphic interfaces so using Currently no image available as the alt value doesn't make much sense.
Since mu is too short's answer's basically the same, I'll delete mine and give you one other possibility.
If this is always about empty strings or objects that are nil, then you could add an or method to Ruby's String and NilClass:
class String
def or(default)
self.empty? ? default : self
end
end
class NilClass
def or(default)
default
end
end
With this you can do:
<%= post.info.or('Currently no information available') %>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With