So I’ve got an object in my database with a date field, except sometimes it will be nil. Is there a way in the view I can show this as a string value. Something like TBA maybe?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
<%= @event.date || "TBA" %>should do it.In response to your comments, yes, you could do this in the model but it’s a bad idea. Why?
First of all, it is about presentation of the data so for that reason it belongs in the view.
Secondly, it could break things. If you did it in the model,
@event.datewould sometimes return a date and sometimes a string. What would happen if you called@event.date.houranddatewas"TBA"? You’d get an error. The only fix would be to check for it everywhere, which would be horrible.If you really are going to be doing it a lot you could create a helper method in
application_helper.rbthat could look something like this:So you could then write in your view:
Which isn’t much less typing but would have the not inconsiderable advantage of restricting the use of the string “TBA” to only one place – which means if you ever need to change it (for I18n purposes for example) – it’s really easy.