【发布时间】:2016-10-05 23:26:58
【问题描述】:
需要以 Epoch 而不是 DateTime 格式存储 created_at 和 updated_at 时间戳。有没有办法改变默认行为,同时让 ORM 来维护时间戳。
当我使用 Rails Generator 生成模型时
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 字段,但这将是应用程序中引入的大量错误代码冗余代码。
我需要以某种方式以纪元格式(自 1970 年以来的时间长)而不是 DateTime 存储时间戳。
谢谢
【问题讨论】:
-
您是否尝试在架构中将
created_at和updated_at列定义为timestamp列? -
是的。但默认情况下它采用 sql 日期时间格式。但我想将其存储为 Epoch 而不是 DateTime
-
对不起,也许我不明白你所说的 Epoch 是什么意思。我以为您的意思是将列存储为自 1970 年以来的秒数,我猜,如果您将列定义为
timestamp列,那么它可能会起作用。您能否详细说明您想要实现的目标? -
更新了我的问题
标签: ruby-on-rails activerecord