Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Rails fixture incorrectly set values for time field #104

Open
dapicester opened this issue Jul 7, 2024 · 0 comments
Open

Rails fixture incorrectly set values for time field #104

dapicester opened this issue Jul 7, 2024 · 0 comments

Comments

@dapicester
Copy link

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant