5

使用 Rails 4.0.0、ruby 2.0p247 和 mysql2 0.3.13 gem。MariaDB 5.5 中我的表中的一列

注意:mariadb 从 5.3 开始支持微秒精度

  `updated_at` timestamp(6) NOT NULL DEFAULT CURRENT_TIMESTAMP,

精度应该是微秒,所以我在我的模型文件中尝试过

before_save :set_update

def set_update
  # also tried
  # self.updated_at = "2013-10-03 12:35:00.123456 -700"  
  # self.updated_at = Time.now.strftime "%Y-%m-%d %H:%M:%S %6N"
  # self.updated_at = Time.now.iso8601(6)
  # doesn't work, still no microseconds

  self.updated_at = Time.now.to_f
end

但在数据库中它仍然是

| updated_at                 |
+----------------------------+
| 2013-10-03 19:35:00.000000 |
+----------------------------+

为什么 rails/activerecord 不存储微秒?

4

2 回答 2

4

让它工作:

将此添加到 config/initializers 中的文件中

class Time
  DATE_FORMATS = {
    :db => '%Y-%m-%d %H:%M:%S.%6N'
  }
end

有关更多信息,请参阅conversions.rb

于 2013-10-03T20:58:20.760 回答
1

为避免出现警告,您可以更新常量而不是覆盖它。在config/initializers/database.rb

Time::DATE_FORMATS.merge!({ db: '%Y-%m-%d %H:%M:%S.%6N' })

您还需要将数据库列的精度设置为 > 1 秒。在迁移中:

class IncreaseTimestampPrecision < ActiveRecord::Migration
  def change
    ActiveRecord::Base.connection.tables.each do |table_name|
      columns = ActiveRecord::Base.connection.columns(table_name)

      # set the precision to microseconds for each datetime column on the table
      columns.select {|col| col.type == :datetime }.each do |column|
        change_column table_name, column.name, :datetime, limit: 6
      end
    end
  end
end

结尾

于 2016-06-09T22:12:38.993 回答