Open
Description
I have a model with a time
field like this:
class MyModel < ApplicationRecord
attribute :my_time, :time_only
end
Then in my fixture I set the value like this:
one:
my_time: "18:00:00"
But when I load the model the field is not set:
instance.my_time
=> nil
Digging a bit deeper I have found that the actual value in the database is this:
instance.my_time_before_type_cast
=> "2000-01-01 18:00:00"
Note that this happens only when using Rails fixtures.
As a quick workaround I added a monkey patch in my initializer:
# config/initializers/tod.rb
if Rails.env.test?
# Fix for Rails fixtures storing a datetime in time fields.
# The time value is prepended with the date "2000-01-01".
module Tod
class TimeOfDay
class << self
old_try_parse = instance_method(:try_parse)
define_method(:try_parse) do |tod_string|
tod_string = tod_string.to_s
tod_string = tod_string[11..] if tod_string.starts_with? "2000-01-01 "
old_try_parse.bind(self).(tod_string)
end
end
end
end
end
I wonder if there's a better way to do that.
Metadata
Metadata
Assignees
Labels
No labels