本文介绍了Ecto&的默认日期时间长生不老药的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚开始工作Elixir&今天的Phoenix,我想将Ecto添加为一个映射器,但是我在使用时间上遇到了一些麻烦。

I've just started working Elixir & Phoenix today, i am trying to add Ecto as a mapper, but i'm having some trouble using time.

这是我的模型。

  schema "users" do
    field :name, :string
    field :email, :string
    field :created_at, :datetime, default: Ecto.DateTime.local
    field :updated_at, :datetime, default: Ecto.DateTime.local
  end

我尝试将默认值设置为created_at和updated_at,但是当我尝试对其进行编译时,出现以下错误。

I'm trying to set the created_at and updated_at per default, but when i try to compile this, i get the following error.

== Compilation error on file web/models/user.ex ==
** (ArgumentError) invalid default argument `%Ecto.DateTime{day: 13, hour: 19, min: 47, month: 2, sec: 12, year: 2015}` for `:datetime`
lib/ecto/schema.ex:687: Ecto.Schema.check_default!/2
lib/ecto/schema.ex:522: Ecto.Schema.__field__/4
web/models/board.ex:9: (module)
(stdlib) erl_eval.erl:657: :erl_eval.do_apply/6

获取文档没有太多帮助,正确的方法是什么?

There is not much help to get in the documentation, what would be the correct way to do this?

推荐答案

:datetime 是Postgres的本机数据类型,以及日期时间;此数据类型映射到两个元素的Elixir元组( {{yy,mm,dd},{hh,mm,ss}} )。 %Ecto.DateTime {} 结构不是两个元素的元组,因此编译错误。

:datetime is the native Postgres data type for, well a datetime; this data type maps to a two-elements Elixir tuple ({{yy, mm, dd}, {hh, mm, ss}}). An %Ecto.DateTime{} struct is not a two-elements tuple, hence the compilation error.

您可能希望将字段的类型设置为 Ecto.DateTime ,它们都应该无缝运行。

You may want to set the type of your fields to Ecto.DateTime, it should all work seamlessly.

是有关原始类型和非原始类型的相关文档。

Here is the relevant documentation about primitive types and non-primitive types.

PS ,您可能还想看看,它是一个宏,基本上可以扩展为您手动编写的内容(它会添加 created_at updated_at 字段,您可以选择它们的类型,默认为 Ecto.DateTime ):

PS you may also want to have a look at Ecto.Schema.timestamps/1, which is macro that expands to basically what you wrote manually (it adds the created_at and updated_at fields and it let's you choose what type they should be, defaulting to Ecto.DateTime):

schema "users" do
  field :name, :string
  field :email, :string
  timestamps
end

这篇关于Ecto&的默认日期时间长生不老药的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-12 18:04