Dienstag, Juli 24, 2007

Rails Bug? Timezone in persistant models

Programming Rails I have realized that there can be a small bug.
When developing a web application there is an option in the "config/environment.rb" file that specifies the default timezone of Active Record, "config.active_record.default_timezone". I set this option to ":utc", so now I thought that I can expect that, when I set an attribute of an object being a model that accepts "Time" as type, then Rails should convert dates of any timezone to the default timezone of Active Record. But it doesnt happen. Only when I read attributes from the database they are handled as dates of default timezone:

# config/environment.rb
config.active_record.default_timezone = :utc

# db/migrate/002_create_user_model.rb
create_table :users do |t|
t.column :name, :string
t.column :created, :datetime

# test/unit/user_test.rb
def test_saving_time_format
now = # localtime = 9:32
bob = users(:bob)
bob.created = now
# bob.created == 9:32 (local) == 7:32 (UTC) == now.utc
# -> success
assert now.utc-2 <= bob.created && bob.created <= now.utc+2; bob.reload
# bob.created == 9:32 (UTC) != 7:32 (UTC) -> fails
assert now.utc-2 <= bob.created && bob.created <= now.utc+2
# convert the time manually to UTC
bob.created = now.utc;; bob.reload
# bob.created == 9:32 (UTC) == now.utc -> successful
assert now.utc-2 <= bob.created && bob.created <= now.utc+2

it fails because rails stored (or better dumped) bob.created localtime to db:
db_record = 9:32 without any convertion and when reloading from db, it handles it as utc time
9:32 (UTC) = 11:32 (localtime).
Instead of dumping the localtime to the db, it would be better when rails converted the time object to UTC and dumped the UTC time to the db!

Maybe I should write a bug report if it is not a feature, but when its a feature its a stupid one!


Labels: , , , , ,


Link erstellen

<< Startseite