Default datetime with Ecto & Elixir

蹲街弑〆低调 提交于 2019-12-05 03:31:30

: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.

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 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
misaelpc

Defaults fields names are :inserted_at and :updated_at but you can merge with your own field names, passing a keyword list

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

You could also consider having the default not be in the schema, but in the migration: "created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP"

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!