如何使用Ecto的时间戳将时间戳添加到现有表中? [英] How to add timestamps to an existing table with Ecto's timestamps?

查看:131
本文介绍了如何使用Ecto的时间戳将时间戳添加到现有表中?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于 insertted_at updated_at 不能为 null 这将不起作用:

Since inserted_at and updated_at can not be null this won't work:

def change do
  alter table(:channels) do
    timestamps
  end
end

**(Postgrex.Error )错误(not_null_violation):列 inserted_at包含空值

是否有一种简单的方法无需复制时间戳的功能?

Is there an easy way to accomplish this without copying timestamps' functionality?

推荐答案

时间戳/ 1 函数接受选项关键字列表,您可以使用它设置默认值。

The timestamps/1 function accepts an options keyword list, you can set the default value with it.

def change do
  alter table(:channels) do
    timestamps default: "2016-01-01 00:00:01", null: false
  end
end


UPDATE Ecto> = 2.1

您需要使用新的类型 NaiveDateTime

def change do
  alter table(:channels) do
    timestamps default: ~N[2017-01-01 00:00:01], null: false
  end
end

如果您还有更多疑问,请查看文档

If you have more doubts take a look at the documentation

这篇关于如何使用Ecto的时间戳将时间戳添加到现有表中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆