Topic: Legacy DB "Zero" dates

There is an application that I'm working on, where the original developers made a date column in the database called 'checked_out', and made the default value be '0000-00-00'. Large portions of the existing application then check to see if the check out date is this value, if so then it has never been checked out, if not then it has the checkout date.

The problem I'm running into is that this is an invalid date, so Ruby can't generate a corresponding date. This is fine when editing, as the Date object just parses it as nil and I can work with that. However on creating a new object, I can't seem to get the system to fill the field with the default value, as rails trys to pass it null, and the field can't have a null value. Further, in order for the data to function properly with the existing application it needs to make the new items have a date of '0000-00-00'.

Any ideas?

Re: Legacy DB "Zero" dates

NOTE: The following feels like a hack.

I got around the issue by first setting the database to accept null values for the column and then adding an after save function which ran an update all to change the null value to the desired default value, since update all just uses the sql. The following is the code:

class Item < ActiveRecord::Base
  ...
  after_save :set_default_date
  ...
  def set_default_date
    Item.update_all({:checked_out => '0000-00-00'}, 'checked_out IS NULL')
  end
end

Re: Legacy DB "Zero" dates

It’s really great posts.