Software As She’s Developed

Mahemoff’s Podcast/Blog – Web, Programming, Usability from the Author of ‘Ajax Design Patterns’ (AjaxPatterns.org)

Software As She’s Developed header image 2

Rails Default Date Gotcha

November 15th, 2011 · No Comments · SoftwareDev

Welcome to Mahemoff's blog on web development, UX, and software development. I most recently worked in developer relations at Google, focusing on Chrome and HTML5, and am now busy baking a few apps independently.

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:

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


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

RUBY:
  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.)

Tags: