Am I misunderstanding cast?

My understanding of Ecto.Changeset.cast/3 is that if I give it well-formed data, it will cast the data into the given data type. But it’s telling me that a date tuple is invalid.

Here’s what I’m doing:

iex(1)> data = %{}
iex(2)> types = %{date_of_birth: :date}
iex(3)> {data, types} |> Ecto.Changeset.cast(%{"date_of_birth" => {1987, 3, 21}}, [:date_of_birth])
#Ecto.Changeset<action: nil, changes: %{},
 errors: [date_of_birth: {"is invalid", [type: :date, validation: :cast]}],
 data: %{}, valid?: false>

Should I be using a different means of converting the date tuple to something that is palatable to ecto?

Create a Date struct with and pass that as date_of_birth.


The main use case is to cast input from a web form POST, so the Ecto date type implements casting from an ISO8601 date string.

If you need to cast from a tuple you can create your own custom date Ecto type that implements this cast. See the docs section on custom types.

1 Like