Non-Primary Key UUIDs in Phoenix
Aug 24, 2017 · 1 min read

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:binary_id. - I’m generating a UUID on record creation by setting the
defaultkey in the migration tofragment(“uuid_generate_v4()”). - 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.
Zachery Moneypenny is a Principal Developer at adorable.io. Rubyist for a long time, with experience in Golang and Javascript as well but moving towards Elixir and loving it.

