Which is prefered when setting default value? Migration or Schema?

I found there’re two ways to set a default value for a field:

  1. In migration https://hexdocs.pm/ecto/Ecto.Migration.html#add/3

    :default - the column’s default value. can be a string, number or a fragment generated by fragment/1

  2. In Schema Ecto.Schema — Ecto v3.11.1

    :default - Sets the default value on the schema and the struct. The default value is calculated at compilation time, so don’t use expressions like DateTime.utc_now or Ecto.UUID.generate as they would then be the same for all records.

Which is prefered? And why? I just don’t see much difference between them.

3 Likes

The difference is that by doing it on the migration, it’s guaranteed by the database that this value will be set. So even if you have another application, or another schema without the :default option set for the field, it will be set to the default value if you don’t set it.

With this in mind, I prefer doing it on the database, but actually, there are cases where it’s not the desired behavior to set the default value every time for every schema. You can use the :default option on field for a schema, and have another schema without it. Something like this for example:

defmodule User.Dummy do
  use Ecto.Schema

  schema "users" do
    field :name, :string, default: "dummy"
    # ...
  end
end

defmodule User do
  use Ecto.Schema

  schema "users" do
    field :name, :string
    # ...
  end
end
6 Likes