Rails的ActiveRecord时间戳使用Epoch格式而不是DateTime格式。

24 浏览
0 Comments

Rails的ActiveRecord时间戳使用Epoch格式而不是DateTime格式。

需要存储创建时间和更新时间的时间戳(Epoch)而非DateTime格式。是否有一种方法可以更改默认行为,同时让ORM继续维护时间戳。

当我使用Rails生成器生成我的模型时

class CreateTenants < ActiveRecord::Migration[5.0]
  def change
    create_table :tenants do |t|
      t.string :tenant_name
      t.string :tenant_owner_name
      t.string :tenant_address
      t.string :tenant_email
      t.integer :pincode
      t.timestamps
    end
  end
end

它不是翻译成的DateTime时间戳。

create_table "tenants", force: :cascade, options: "ENGINE=InnoDB DEFAULT CHARSET=utf8" do |t|
    t.string   "tenant_name"
    t.string   "tenant_owner_name"
    t.string   "tenant_address"
    t.string   "tenant_email"
    t.integer  "pincode"
    t.datetime "created_at",        null: false
    t.datetime "updated_at",        null: false
  end

我知道我可以直接创建两列,并在每次添加/更改记录时手动更改created_at和updated_at字段,但这会在应用程序中引入大量不好的冗余代码。

我需要的是以Epoch格式(自1970年以来的时间)而非DateTime格式存储时间戳。

谢谢

admin 更改状态以发布 2023年5月23日
0
0 Comments

您没有指定使用的DB,因此我假设在此处使用的是MySQL。 结果Rails支持时间戳的所有变体: DATETIMEDATETIMETIMESTAMP,甚至是INTEGER。 有关这些类型之间的差异的更多信息,请参见MySQL文档,了解有关Rails如何理解它们的信息,请参见此答案。

1)TIMESTAMP时间戳列

如果您要将时间戳存储在TIMESTAMP类型列中,请在迁移中尝试以下技巧(请注意' timestamp '中的空格,否则Rails将始终将列创建为datetime ,而不是timestamp仅是Rails中datetime的别名):

create_table :tenants do |t|
  # ...
  #t.timestamps (remove the default timestamps definition) 
  t.column :created_at, 'timestamp ', null: false
  t.column :updated_at, 'timestamp ', null: false
end

处理记录时,时间戳将显示为普通的日期时间,但将作为TIMESTAMP存储在DB中,从而每个记录可以节省几个字节:

Tenant.create!
# => SQL (0.1ms)  INSERT INTO `tenants` (`created_at`, `updated_at`) VALUES ('2016-06-08 08:45:20', '2016-06-08 08:45:20')
=> #

当然,您可以始终使用to_i方法将日期时间转换为自纪元以来的秒数:

Tenant.last.created_at.to_i
# => 1465375595

2)INTEGER 时间戳列

如果您确实要将时间戳存储为自纪元(1970年)以来的秒数,只需将时间戳列定义为INTEGER 类型列:

create_table :tenants do |t|
  # ...
  #t.timestamps (remove the default timestamps definition)
  t.integer :created_at, null: false
  t.integer :updated_at, null: false
end

然后,在Rails中记录的时间戳也会显示为整数:

Tenant.create!
# => SQL (0.2ms)  INSERT INTO `tenants` (`created_at`, `updated_at`) VALUES (1465375595, 1465375595)
# => #

0