charleyh
charleyh

Reputation: 2053

Time attribute gets changed when saved to database in Rails

I have a model, called event, with a time attribute. I'm setting it to Time.now, and it I log the time on the object before save, its a second or two after the current time, as expected. But once the object is saved and then found in the database, the time is different, with a the date part being January 1st, 2000. What's causing this, and what can I do to make sure my times are saved correctly? EDIT: the column type is time, database is SQLite.

Upvotes: 2

Views: 2657

Answers (1)

Ecnalyr
Ecnalyr

Reputation: 5802

It sounds like you may be saving a time object rather than a date object.

Active record allows you to use time, date, and datetime objects.

If you are using a time or date object, however, they are still kind of (bad way of explaining it, see the linked response below for more details) full datetime objects. When you read them the date will be present on time objects (typically as January 1'st, 2000).


What can I do to make sure my times are saved correctly?

If saving / reading the full datetime is important for this field, you may want to consider changing the migration representing your model to use:

object.datetime

. . . rather than:

object.time

See this response for some more details: https://stackoverflow.com/a/3929047/1026898

Upvotes: 4

Related Questions