A little gotcha with custom setters for datetime attributes is, that when setting an attribute through ‘write_attribute’ it is not converted to UTC (or whatever else your default time zone is).
This problem can easily be reproduced:
./script/generate model Thing a:datetime b:datetime
My model:
class Thing < ActiveRecord::Base def b=(d) write_attribute(:b, d) end end
My tests:
require 'test_helper' class ThingTest < ActiveSupport::TestCase test "a and b" do d = DateTime.now t = Thing.new t.a = d t.b = d t.save assert_equal t.a, t.b t.reload assert_equal t.a, t.b end end
The second assertion will fail. Is this intended or a bug?
Quick fix:
def b=(d) d = d.utc write_attribute(:b, d) end




[...] Update: Be careful if you use this with Datetime attributes. [...]