Dirty attributes were recently added to Rails and they’re quite useful. However, I ran into a problem where a dirty date/time attribute was losing its time zone information after a save. I was doing a comparison between two dates in a before_update callback like so:
before_update do if started_at.to_s(:abbrev_date) != started_at_was.to_s(:abbrev_date) errors.add :started_at, "cannot be set to a different day" end end
The started_at
date was coming back in the Eastern time zone as expected. The started_at_was
attribute, which was supposed to reflect the value prior to the update, was coming back as a UTC date/time. I would expect it to be returned in the Eastern time zone too. Apparently, I’m not alone in this assumption because a ticket was opened for this issue last month.
An official fix hasn’t been made yet, but I got around the problem by calling in_time_zone
on my dirty attribute:
before_update do if started_at.to_s(:abbrev_date) != started_at_was.in_time_zone.to_s(:abbrev_date) errors.add :started_at, "cannot be set to a different day" end end