Rails inserting invalid datetimes in created_at and updated_at

I am using Rails 3.2.2 on Ruby 1.8.7 with mysql2 0.3.11 (against a mysql 14.14 server), and sometimes a created_at or updated_at value will be an invalid DateTime, and cause my app to throw an exception with the message "Invalid date: 2022-03-00 00:00:00".

I am not explicitly creating, setting, reading, or doing anything with the created_at and updated_at columns.

Inspecting the table through a mysql client, for the most part, the value in each of these columns is "0000-00-00 00:00:00", which ends up as nil in Rails. However, several rows show values such as "2022-03-00 00:00:00" (they are all different, though as far as I can tell, all in 2022).

Interestingly, I can't even run .destroy() from Rails, because it can't create the object.

What could be setting invalid dates for those columns?

Edit: This is happening for all tables. Here is my schema.rb, and all of the migrations for one of the tables: https://gist.github.com/2930655

Edit2: I solved it myself (see my answer below), but would appreciate if you'd weigh in on if it's a bug, and if so, which package the bug is with (ActiveRecord?).

Answers


It turns out that this was happening because I'd overloaded Time#to_s, causing invalid values to be sent in SQL (it was sending HH:MM:SS for DateTimes).

MySQL and SQLite both fail to parse DateTimes in this format, and result in garbage values, however, SQLite's values are never "invalid" according to Ruby, so I never noticed this during development.

Now, when I am saving an object that has a Time or DateTime in another column, and I set it to a Time/DateTime object, it is set correctly, so I am inclined to say that this is a bug.


Need Your Help

TypeError: undefined is not a function in Angular Resource

javascript angularjs angularjs-directive angularjs-scope angularjs-resource

When trying to poll a custom method copies on an AngularJS Resource I get the following error at angular.js:10033: (The method copy works just fine.)

Java serialization error while sending byte array to webservice

java android ksoap2

I am getting an error: Java.lang.RuntimeException: Cannot serialize : -119 while executing call method in HttpTransportSE.