rails: :time doesn't follow the same dst behavior of :datetime
Steps to reproduce
begin
require 'bundler/inline'
rescue LoadError => e
$stderr.puts 'Bundler version 1.10 or later is required. Please update your Bundler'
raise e
end
gemfile(true) do
source 'https://rubygems.org'
gem 'activerecord', '>= 5.0.0.beta4'
gem 'sqlite3'
end
require 'active_record'
require 'minitest/autorun'
require 'logger'
# Ensure backward compatibility with Minitest 4
Minitest::Test = MiniTest::Unit::TestCase unless defined?(Minitest::Test)
ActiveRecord::Base.time_zone_aware_types << :time
ActiveRecord::Base.time_zone_aware_attributes = true
ActiveRecord::Base.establish_connection(adapter: 'sqlite3', database: ':memory:')
ActiveRecord::Base.logger = Logger.new(STDOUT)
ActiveRecord::Schema.define do
create_table :posts, force: true do |t|
t.time :time_offset_bug
end
end
class Post < ActiveRecord::Base
end
class BugTest < Minitest::Test
def test_offset_bug
Time.zone = 'Brasilia'
assert_equal "-03:00", Time.current.formatted_offset # this works
post = Post.create!(time_offset_bug: "14:00")
# this blows up
assert_equal "-03:00", post.time_offset_bug.formatted_offset
assert_equal "2000-01-01 17:00:00 UTC", post.time_offset_bug.utc.to_s
end
end
Expected behavior
post.time_offset_bug.utc_offset should be -3 (and the time saved in the database should be saved in UTC)
Actual behavior
post.time_offset_bug.utc_offset is -2 and the time saved in the database isn’t saved in UTC.
System configuration
Rails 5.0.0.beta4(happens at master as well)
ruby 2.3.1p112 (2016-04-26 revision 54768) [x86_64-darwin15]
About this issue
- Original URL
- State: closed
- Created 11 years ago
- Comments: 29 (15 by maintainers)
Workaround
config/initializers/time_only.rb
app/models/availability.rb
Rails force the date part of that object to be 2000-01-01 on this line of ActiveModel:
https://github.com/rails/rails/blob/main/activemodel/lib/active_model/type/time.rb#L73
So, if you need to change this behavior for the entire application, I think you will need to replace/monkey-patch this method, changing the hardcoded string by the
::Date.todayfrom the previous workaround, OR prepending this class and replacing the returned object date part, something like this:config/initializers/time_casted_for_today.rb
@Paul-Bob After some time using the TimeOnly type I found the workaround required more adaptations to handle some cases for comparisons, conversions, and other requirements from places like forms, etc. But I agree with you that the arbitrary date is pretty unexpected and leads to mistakes
Also just to clarify one last point before I log off, I would love to improve this behavior as I agree there is something unintuitive. I just don’t think there is an alternative that would work here.
On Mon, May 9, 2016, 12:30 PM Sean Griffin sean@seantheprogrammer.com wrote: