Search code examples
elixirecto

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


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?


Solution

  • 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