DEV Community

loading...

How to: use UUID as Primary Keys in Phoenix

estevanjantsk profile image Estevan Jantsk ・1 min read

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
    end
  end
end
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 :).

Discussion

pic
Editor guide
Collapse
pehagg profile image
Peter Hägg

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