Non-Primary Key UUIDs in Phoenix

Photo by Thomas Lefebvre on Unsplash

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.

The code for the migration and the schema file

There are three key things to note in the code above:

  • The database field is set to :uuid while the schema field is set to :binary_id.
  • I’m generating a UUID on record creation by setting the default key in the migration to fragment(“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: true in 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.