Rails Default Date Gotcha

This had me going for a while!

I wanted to default a field to the epoch, i.e. some decades ago, or older. That’s because a batch process will work on the records with the oldest such field, so setting the field to epoch guarantees they’ll get priority initially.

I had a migration like such:

  1. t.datetime :acted_on, :default => 0  ### BAD

After some debugging, I notice FactoryGirl is setting the field to null. The fix is:

  1. t.datetime :acted_on, :default => DateTime.new ### GOOD

Note it’s DateTime.new for epoch, not DateTime.now, which will be the present time. (And you probably wouldn’t want that, because it would be the time you run the migration, not the time a given record is actually created. If you want creation time, use a before_create callback.)

Leave a Reply