Non-Primary Key UUIDs in Phoenix
This is a quick one.
I needed to add support to my Elixir/Phoenix application for a database field and corresponding schema field that was a UUID, but was not a primary or foreign key.
The challenge was that I found quite a few posts on how to enable UUIDs as primary keys but Ecto has some syntactic sugar for setting that up, whereas the specific combination of migration and schema declarations are slightly different in non-key situations.
There are three key things to note in the code above:
- The database field is set to
:uuidwhile the schema field is set to
- I’m generating a UUID on record creation by setting the
defaultkey in the migration to
- A column value generated in the database is not read back into the struct by default; you must set
read_after_writes: truein the schema declaration in order to get that value back out of the database after creates and updates.