Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add timestamps to an existing table with Ecto's timestamps?

Tags:

elixir

ecto

Since inserted_at and updated_at can not be null this won't work:

def change do
  alter table(:channels) do
    timestamps
  end
end

** (Postgrex.Error) ERROR (not_null_violation): column "inserted_at" contains null values

Is there an easy way to accomplish this without copying timestamps' functionality?

like image 937
Philip Claren Avatar asked Mar 02 '16 10:03

Philip Claren


1 Answers

The timestamps/1 function accepts an options keyword list, you can set the default value with it.

def change do
  alter table(:channels) do
    timestamps default: "2016-01-01 00:00:01", null: false
  end
end


UPDATE Ecto >= 2.1
You'll need to use the new type NaiveDateTime

def change do
  alter table(:channels) do
    timestamps default: ~N[2017-01-01 00:00:01], null: false
  end
end

If you have more doubts take a look at the documentation

like image 153
josemrb Avatar answered Oct 04 '22 14:10

josemrb