1
votes

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?

2

2 Answers

11
votes

To set a default value of the column in the database, you need to use a migration. Setting it in the schema declaration will not affect the database. Something like the following should work in a migration and make those two columns default to NOW():

alter table(:users) do
  modify(:inserted_at, :timestamp, default: fragment("NOW()"))
  modify(:updated_at, :timestamp, default: fragment("NOW()"))
end
0
votes

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