Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails Format Nil Date

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?

like image 251
benedict_w Avatar asked Nov 19 '12 12:11

benedict_w


2 Answers

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) %>
like image 117
honktronic Avatar answered Nov 12 '22 18:11

honktronic


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>
like image 26
Rodrigo Castro Avatar answered Nov 12 '22 19:11

Rodrigo Castro