如何使用Ecto的时间戳将时间戳添加到现有表?
问题描述:
由于inserted_at
和updated_at
不能null
这是行不通的:如何使用Ecto的时间戳将时间戳添加到现有表?
def change do
alter table(:channels) do
timestamps
end
end
** (Postgrex.Error) ERROR (not_null_violation): column "inserted_at" contains null values
是否有一个简单的方法来做到这一点不复制timestamps
“的功能?
答
timestamps/1
函数接受一个选项关键字列表,您可以使用它设置默认值。
def change do
alter table(:channels) do
timestamps default: "2016-01-01 00:00:01", null: false
end
end
UPDATE外生> = 2.1
你需要使用新的类型NaiveDateTime
def change do
alter table(:channels) do
timestamps default: ~N[2017-01-01 00:00:01], null: false
end
end
如果您有更多的怀疑看看的documentation
答
我想你会得到这个当你尝试更新的记录,我能想到2个可能的解决方案,您既可以在你的餐桌触摸inserted_at列通过运行一个UPDATE查询或添加功能,以您的外生模型,像这样
def create_changeset(model, attrs) do
model
|> cast(attrs, @required_fields, @optional_fields)
|> update_inserted_at
end
defp update_inserted_at(changeset) do
# check if the updated field is null set a new date
end
外生2.0已取消这个选项:(可能最好的解决办法是手动添加两个字段。 –
原来的解决方案刚刚在Ecto 3.2中工作:) ...''timestamps default:“2016-01-01 00:00:01”,null:false' - 这是原始未更新的答案。 –