Monday, April 13, 2009

DateTime with zone support in rails fixture

To get time with zone support we usually call, Time.now.utc

But if we use Time.now.utc in fixture like,

fixture1:
deadline: <%= Time.now.utc %>

It gives an error:

ActiveRecord::StatementInvalid: Mysql::Error: Incorrect datetime value: 'Sun Apr 12 11:40:05 UTC 2009' for column 'deadline' at row 1: INSERT INTO job_assignments (job_id, updated_at, id, deadline, transporter_fee, transporter_id, created_at, state) VALUES (245383586, '2009-04-12 09:40:07', 809788707, 'Sun Apr 12 11:40:05 UTC 2009', 75, 468814034, '2009-04-12 09:40:07', 'assigned')

Because fixtures calls a default to_s function for each fields to create the insert script. Fixtures does not save records through Models. Time.now.utc.to_s generates a string which is not in the format to save date time in mysql. To generate such format we need to call Time.now.utc.to_s(:db). So the fixture turned out like,

fixture1:
deadline: <%= Time.now.utc.to_s(:db) %>

2 comments:

Unknown said...

Liked the post. I will save my time in future.

Anonymous said...

finally a solution that works ,,,,