Allan
Allan

Reputation: 2606

'Time' being changed to a 'Datetime' after being added to a hash

My controller creates something called start_time. When I print start_time's value before it's added to a LittleClassSession hash, here's what I get:

22:45:00

Okay, it looks like a value with the type time. After it's added to the hash, I ask the controller what the :start_time value is.

@little_class_session = LittleClassSession.new({
  ...
  :start_time => start_time
})

puts @little_class_session.start_time

Here's what it puts:

2000-01-01 22:45:00 UTC

It appears to be formatted like a datetime, but asking what the .class of the start_time attribute is returns:

Time

The LittleClassSession start_time column is a time in the table (I can verify this by checking the type in the Rails console) but was a datetime when the model was created.

What could be causing this?

Upvotes: 0

Views: 91

Answers (1)

Robert Nubel
Robert Nubel

Reputation: 7532

While your database may support a "time" column (meaning just a time with no date information), Rails by default does not (largely because neither does Ruby's standard library -- even a Time contains date information). As such, when you assign it to your model, Rails is coercing it into the type it knows how to deal with, DateTime. So, you have a few options:

  1. Ignore the date part of the time when you use it.

  2. Use a gem like tod to deal with your time-only types, and follow the guidelines in the README for hooking it up to Rails.

  3. Store start_time_hour and start_time_minutes in two separate columns, and work with them as needed (e.g, Date.current + start_time_hour.hours + start_time_minutes.minutes).

Hope that helps!

Upvotes: 2

Related Questions