Reputation: 3608
I'm trying to format dates in a Rails view.
<td><%= l order.ship_date, :format => :long %></td>
This doesn't work if the date is nil:
Object must be a Date, DateTime or Time object. nil given.
What's the best "Rails" solution?
Upvotes: 12
Views: 6669
Reputation: 363
Three options:
1) Make sure you never have a nil date. Depends on the product you're trying to create, but in many cases it wouldn't make sense to have a nil date displayed. If, for your product, nil dates are reasonable, this won't work.
2) Write view code everywhere to hide the nil:
<%= order.ship_date ? l(order.ship_date, :format => :long) : 'Date unavailable' %>
3) Write a helper function to do this for you:
def display_date(date, message='Date unavailable')
date ? l(date, :format => :long) : message
end
Then all you have to do in each place you want this date treatment is to say:
<%= display_date(order.ship_date) %>
Upvotes: 10
Reputation: 1583
Just add a failsafe if the object is nil:
<td><%= l(order.ship_date, :format => :long) if order.ship_date %></td>
If you want to display something in case it's nil:
<td><%= order.ship_date ? l(order.ship_date, :format => :long) : "Some text" %></td>
Upvotes: 11