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?
Yes!
Check out @timestamps_opts
at https://hexdocs.pm/ecto/Ecto.Schema.html#module-schema-attributes
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
Thanks @idi527 ! I think that will work well, I’ll try it out.
Stumbled over this old topic and wanted to mention how easy it is to customize the generators. So for the schema you’d just mkdir -p priv/templates/phx.gen.schema && cp deps/phoenix/priv/templates/phx.gen.schema/schema.ex priv/templates/phx.gen.schema
then edit your personal copy of the schema to include the @timestamp_opts
that you want (or use
the module you wrote). Voila, all new schemas you generate will now have your custom addition.