'Phoenix framework Ecto give default value to timestamp

I would like to know how auto fill "updated_at" and "inserted_at" columns generated by timestamp().

The goal is to not specify these values because it has to be automatic. I know how to do with other columns.

schema "users" do
  field :newsletter, :boolean, default: false

  timestamps(type: :utc_datetime)
end

I have tried

schema "users" do
  field :newsletter, :boolean, default: false
  field :inserted_at,:utc_datetime, default: :utc_datetime
  field :updated_at,:utc_datetime, default: :utc_datetime
end

But it seems it doesn't work or changes are not taken in account when I run:

mix ecto.migrate

Is my code wrong or do I use the wrong command line?

In my SQL schema I have

newsletter  BOOLEAN DEFAULT FALSE NOT NULL,
inserted_at TIMESTAMP             NOT NULL,
updated_at  TIMESTAMP             NOT NULL,

And doesn't matter what I try, I can't have "DEFAULT TIMESTAMP" on the two last lines.

Must I drop the table before it can work?



Solution 1:[1]

As the timestamps() call to add(), you can pass directly the option :default and use a fragment to set it all in one step.

schema "users" do
  field :newsletter, :boolean, default: false

  timestamps(default: fragment("NOW()"))
end

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 JuliSmz