简体   繁体   English

使用Ecto和Elixir的默认日期时间

[英]Default datetime with Ecto & Elixir

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. 我今天刚刚开始使用Elixir和Phoenix,我试图将Ecto添加为映射器,但是我在使用时间时遇到了一些麻烦。

This is my model. 这是我的模特。

  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

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. 我试图在默认情况下设置created_at和updated_at,但是当我尝试编译它时,我收到以下错误。

== 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? 获取文档没有太大帮助,这样做的正确方法是什么?

Defaults fields names are :inserted_at and :updated_at but you can merge with your own field names, passing a keyword list 默认字段名称为:inserted_at:updated_at但您可以合并自己的字段名称,并传递关键字列表

schema "users" do
  field :name, :string
  field :email, :string
  timestamps([{:inserted_at,:created_at}])
end

:datetime is the native Postgres data type for, well a datetime; :datetime是本机Postgres数据类型,以及日期时间; this data type maps to a two-elements Elixir tuple ( {{yy, mm, dd}, {hh, mm, ss}} ). 此数据类型映射到两个元素的Elixir元组( {{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. 您可能希望将字段类型设置为Ecto.DateTime ,它应该都可以无缝地工作。

Here is the relevant documentation about primitive types and non-primitive types. 以下是有关基本类型和非基本类型的相关文档。

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 ): PS你可能还想看看Ecto.Schema.timestamps/1 ,它是宏,它基本上扩展到你手动编写的内容(它添加了created_atupdated_at字段,它让你选择它们应该是什么类型,默认为Ecto.DateTime ):

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

您还可以考虑让默认值不在架构中,但在迁移中: "created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM