Change default timestamp type?

I’d like all of the schemas in my project to use timestamps(type: :utc_datetime) but I would prefer for developers to not need to remember to do that every time. Is there a good way to change the project’s defaults so using the regular timestamps() defaults to :utc_datetime type?

:wave:

Yes!

Check out @timestamps_opts at https://hexdocs.pm/ecto/Ecto.Schema.html#module-schema-attributes

:wave:

Is there a good way to change the project’s defaults so using the regular timestamps() defaults to :utc_datetime type?

Yes!

You can to define a custom YourApp.Schema module that would export a using macro which would use Ecto.Schema and then configure the schema attributes.

defmodule YourApp.Schema do
  defmacro __using__(_opts) do
    quote do
      use Ecto.Schema
      @timestamps_opts [type: :utc_datetime]
    end
  end
end

and then in your schemas

defmodule YourApp.Resource do
  use YourApp.Schema

  schema "resources" do
    # ...
  end
end
3 Likes

Thanks @idiot ! I think that will work well, I’ll try it out.