Question

I use strftime to format my raw time as the text of an input box. Usually, when I use strftime I check if the object is nil to prevent errors by using unless nil? However it doesn't seem like I can use that here:

<%= text_field_tag :event_date, @event.event_date.strftime("%m/%d/%Y at %I:%M%p"), :size=>30 %>

I removed the unless because it was throwing an error. How can I make sure this statement works if @event.event_date is nil?

Thanks

Was it helpful?

Solution

One trick is to use try.

<%= text_field_tag :event_date, @event.event_date.try(:strftime, "%m/%d/%Y at %I:%M%p"), :size=>30 %>

Or just check if event_date is set:

<%= text_field_tag :event_date, (@event.event_date && @event.event_date.strftime("%m/%d/%Y at %I:%M%p")), :size=>30 %>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top