Building on Top of Ecto’s Types
Learn how to build custom types on top of Ecto's types.
Map Ecto’s types
When we talked about schemas, we had a table that showed how Ecto’s types map to an Elixir type.
For example, if we use :string
when defining a field, Ecto treats the value as a String
on the Elixir side, then uses whatever column definition our database uses to store string values.
If we think about it, several different kinds of data can be stored as a string, such as a date, a UUID, a list of values, or even a complex data collection in JSON. These can be stored as a string and later parsed into a more meaningful type when brought into Elixir. In our first look at creating custom types, we take a value stored as a simple type in the database and turn it into a different kind when brought into Elixir.
Create a custom datetime type
We’d like to add support for working with dates and times in the Unix time format. We know that Ecto’s datetime
type can store and retrieve timestamps to and from the database, but this type cannot handle the Unix format. We can cast strings in ISO-8601 format (2017-11-05T20:49:41Z)
, but if we tried to give it something like Date(1509914981)
, it wouldn’t work.
To make this work, we can create a custom type built on Ecto’s datetime
type and create a slightly smarter version. To add our custom type, we need to create a module that implements the Ecto.Type
behavior, which looks like the following.
Get hands-on with 1400+ tech skills courses.