Default datetime with Ecto & Elixir

I just started working with Elixir and Phoenix today, I'm trying to add Ecto as a mapper, but I am having problems using time.

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 am trying to set created_at and updated_at by 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 

You can find little in the documentation, what would be the right way?

+7
postgresql elixir ecto
source share
3 answers

:datetime is a native Postgres data type for, as well as datetime; this data type is mapped to two elements of the Elixir tuple ( {{yy, mm, dd}, {hh, mm, ss}} ). The structure of %Ecto.DateTime{} not a two-element tuple, therefore a compilation error.

You might want to set the field type to Ecto.DateTime , it should work without problems.

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

PS , you can also take a look at Ecto.Schema.timestamps/1 , which is a macro that extends basically what you wrote manually (it adds the created_at and updated_at fields, and you can choose what type they should be, by default Ecto.DateTime ):

 schema "users" do field :name, :string field :email, :string timestamps end 
+12
source share

The default field names are :inserted_at and :updated_at , but you can combine with your own field names by passing a list of keywords

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

You might also think that the default value is not specified in the schema, but during the migration: "created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP"

+2
source share

All Articles