2

So Rails 4.2 starts to support fractional seconds for MySQL. However it requires a migration of column change from datetime to datetime(6). Currently we do not want to do this, and just want to ignore fractional seconds as we have always been doing before.

Rails is not smart enough to see that my datetime has precision 0 and change queries accordingly, so a lot of our spec broke. For example we assert to "select all Foo created within the last hour", but values are persisted without milliseconds, but select statements still uses milliseconds, so lots of records won't be selected.

Before Rails 4.2:

where("foo_at >= ?", 1.day.ago) => foo_at >= '2015-11-02 04:48:18'

In Rails 4.2:

where("foo_at >= ?", 1.day.ago) => foo_at >= '2015-11-02 04:48:18.934162'

Is there a global setting to force AR queries to strip out fractional/milliseconds as it has been doing before?

Community
  • 1
  • 1
lulalala
  • 17,572
  • 15
  • 110
  • 169

2 Answers2

3

There is no official way to turn it off, but you could overwrite the behavior,

module ActiveRecord
  module ConnectionAdapters
    class Mysql2Adapter < AbstractMysqlAdapter
      def quoted_date(value)
        super
      end
    end
  end
end

It is in https://github.com/rails/rails/blob/v4.2.5/activerecord/lib/active_record/connection_adapters/mysql2_adapter.rb#L77-L83

And you could remove it in Rails 5, the commit in rails 5 https://github.com/rails/rails/commit/bb9d20cf3434e20ac6f275e3ad29be42ebec207f should Format the time string according to the precision of the time column

Ilake Chang
  • 1,542
  • 1
  • 14
  • 19
1

From reading Rails source for 4.2.x branch, I don't see any option to change that.

I see a merged PR, which will see what the database column's precision is, and build the sql datetime string according to that precision. This should eliminate my issue that my spec broke due to mismatch of precision between persisted data and queries. However this is not merged in 4.2.x so it probably will only be available in Rails 5.

lulalala
  • 17,572
  • 15
  • 110
  • 169