Wednesday, July 25, 2007

How to handle Time fields in MySQL and Ruby on Rails

One of these days while I was working in a small application created in Ruby on Rails I came across a field in the database with data type Time. The interesting thing was that Rails does not support Time fields, it supports only Date or Datetime, so what to do?

Since I had to handle Time fields not dates, I had to do some tricks to make this work. I'm going to share with you, in a high level, what I did.

First, in the RHTML page I handled the time (hour and minutes) using my own fields, maybe HTML selects with the possible time values.

Next, I created some Javascript function which would post the time as a String or numeric value to the controller, then in the controller you convert the value to a String notation with the format "HH:MM", for example "08:30" or "14:25".

Then, you create a Ruby Time object using your String time as follows:
timeObj = Time.parse("8:15")

This will create a Time object with the current system date and the given hour and minutes you set.

Finally, when you store your Time object in database, MySQL will truncate the date and store only the time value which is exactly what you wanted to do in the first place.

I hope this helps!!