DEV Community

Estevan Jantsk
Estevan Jantsk

Posted on

How to: use UUID as Primary Keys in Phoenix

So I decided to use UUIDs as primary keys for the resources I am creating in my webapp. The reason is cause I don't like the default one "auto increment integer".

So how to achieve this in Phoenix?

1. Add a custom schema

The idea with the code below is to override Ecto.Schema with our new config

# lib/your_app/schema.ex

defmodule YourApp.Schema do
  defmacro __using__(_) do
    quote do
      use Ecto.Schema
      @primary_key {:id, :binary_id, autogenerate: true}
      @foreign_key_type :binary_id
Enter fullscreen mode Exit fullscreen mode

Now, on your schemas you should use use YourApp.Schema instead of Ecto.Schema

2. Fix your Migration!

This one is a very important step. The reason why is because by default when your run your migration it will try to create your tables using the default id (auto increment integer) to fix this is very simple

# config/config.exs

config :your_app, YourApp.Repo, migration_primary_key: [name: :id, type: :binary_id]
Enter fullscreen mode Exit fullscreen mode

Now when you run your migrations to create your tables the id will be of type binary_id :D.

And that's it. Profit :).

Top comments (2)

pehagg profile image
Peter Hägg • Edited

Alternatively, if you're starting off fresh, you can just pass in --binary-id when creating your Phoenix project, .e.g. mix --binary-id hello.

chakrihacker profile image
Subramanya Chakravarthy

How do I use uuid for new table with primary key?