ActiveRecord timezones without Rails
I was using Active Record in a batch application to manipulate some data, and I needed the timezone handling built into the newer versions. But I had a hell of a time trying to figure out how to make it all work.
In plain Rails, it’s simple:
Rails::Initializer.run do |config| config.time_zone = 'Pacific Time (US & Canada)' end
But I wasn’t running Rails proper, and didn’t want to pull in the whole Rails boot sequence. So the Rails::Initializer call didn’t work. To do it manually, time zone config turns out it’s a 3 lines of setup calls:
require 'activerecord' Time.zone = "Pacific Time (US & Canada)" ActiveRecord::Base.time_zone_aware_attributes = true ActiveRecord::Base.default_timezone = "Pacific Time (US & Canada)"
When you do that, time zone attributes work both going into the database, and coming back out. If you miss the last line, they’ll just not work coming out, which is a damn confusing thing to deal with.
Ohh, and one other thing I ran into when getting this setup is that AR pulls in Active Support, which in turn pulls in Builder (to hack xml support or something). Just watch out for that, you’ll get weird crashes if you don’t have builder installed. Honestly, I just went and commented out the areas of Active Support that did it, I didn’t want builder anyway.
June 24th, 2009 at 7:39 pm
I just wanted to thank you for posting this info. It exactly addressed the situation I was facing. Thank-you, thank-you, thank-you!