Wednesday, December 2, 2009

Issue under Rails formatting date time values

I think Rails has a very nice way of handling the format of dates and times in the views. You can substitute your own formats when the default one used by rails doesn't meet your needs. There are numerous postings on how to do this and I've referenced a few at the bottom of this article. Read one of those articles if you need to find out how to do this. I'm going to cut right to the reason for this post. I had setup my own date format as such:

Time::DATE_FORMATS[:for_column] = "%b %d %Y (%I:%M %p)"

Then in my view I was using it like this:

<td style="text-align: center"><%= user.last_login_at.to_s(:for_column) -%></td>

Naturally I was doing this in several views and unfortunately some were working and some were not. I was on occasion getting the error:

"wrong number of arguments (1 for 0)"

on the call to user.last_login_at.to_s(:for_column)

Since I had a few working examples I spent quite a bit a time comparing the working examples with the failing ones. I found old posts on issues with concerning this topic and apparently there have been several issues with date time formatting under rails (no surprise here) and unfortunately a few of the posts sent me down the wrong path. After about an hour of wasted time I discovered the ticket #1701 on Lighthouse which shed some light on the subject. It turns out that the alias for to_s is not setup properly when the datetime field is nil. That means the to_s method of the nil object is being called and it doesn't have any arguments.

My work around for this situation was to create a helper method. Hopefully you find this post useful and it saves you the hour I lost.

    def fixDateTimeFormatting( field )



NOTE: These are fairly old posts and contain information that is useful but not necessarily accurate for Rails 2.0+ so keep that in mind while reading.

practical ecommerce – Custom Date Output Using Rails

Ruby Forum – Changing default date format in Rails

APIDock – to_formatted_s

No comments:

Post a Comment