activerecord是否截断时间戳精度?

时间:2013-10-03 19:50:13

标签: mysql ruby-on-rails ruby activerecord ruby-on-rails-4

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

注意:自5.3以来,mariadb已获得微秒精度支持

  `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不存储微秒?

2 个答案:

答案 0 :(得分:3)

让它发挥作用:

将此添加到config / initializers

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

请参阅conversions.rb了解详情。

答案 1 :(得分:0)

要避免警告,您可以更新常量而不是覆盖它。在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