Default :date in Migration

Simple question, how to add a default Ecto.Date value to a field without using timestamp?

alter table(:registro) do
      modify :data,  :date,    [null: false, default: Ecto.Date.utc()]
end

I know that this isnt the right way to do, but the exception still bugs me
(ArgumentError) unknown default #Ecto.Date<2017-03-21> for type :date. :default may be a string, number, boolean, empty list or a fragment(…)

Thanks

1 Like

the exception message is actually pretty good… you need to use a fragment - see docs for solution :slight_smile:

https://hexdocs.pm/ecto/Ecto.Migration.html#fragment/1

2 Likes

Ok, can you explain whats a fragment and how to use it?

create table(:posts) do
  add :inserted_at, :naive_datetime, default: fragment("now()")
end

the fragment() function is calling a now() function?

3 Likes

I believe a fragment is best described as ‘custom sql’

the now() function is a function in postgres https://www.postgresql.org/docs/9.6/static/functions-datetime.html#FUNCTIONS-DATETIME-CURRENT

modify :data, :date, [null: false, default: fragment("now()")]

should work, although you are using a date field, so I’m not 100% - you might need to use:
modify :data, :date, [null: false, default: fragment("current_date")]

3 Likes

Thank you very much! =)

2 Likes