Skip to content

Instantly share code, notes, and snippets.

@stevedomin
Last active July 12, 2023 01:32
Show Gist options
  • Star 43 You must be signed in to star a gist
  • Fork 7 You must be signed in to fork a gist
  • Save stevedomin/0ea9d9af96b565cbd0b7 to your computer and use it in GitHub Desktop.
Save stevedomin/0ea9d9af96b565cbd0b7 to your computer and use it in GitHub Desktop.
Using UUIDs as primary key with Ecto
defmodule MyBlog.Repo.Migrations.CreatePost do
use Ecto.Migration
def change do
create table(:posts, primary_key: false) do
add :id, :uuid, primary_key: true
add :body, :string
add :word_count, :integer
timestamps
end
end
end
defmodule MyBlog.Post do
use MyBlog.Web, :model
@primary_key {:id, :binary_id, autogenerate: true}
schema "posts" do
field :body, :string
field :word_count, :integer
timestamps
end
@required_fields ~w(body word_count)
@optional_fields ~w()
@doc """
Creates a changeset based on the `model` and `params`.
If `params` are nil, an invalid changeset is returned
with no validation performed.
"""
def changeset(model, params \\ nil) do
model
|> cast(params, @required_fields, @optional_fields)
end
end
@zeejers
Copy link

zeejers commented Jan 26, 2021

Thanks for the gist. Just to point out, if you need to create a reference to the uuid based foreign key, you'll want to use references("table", type: :uuid) in your reference migration, like this:

def change do
    alter table("comments") do
      add :post_id, references(:posts, type: :uuid)
    end
  end

And for the schema

schema "comments" do
    field :body, :string
    belongs_to :post, MyBlog.Post, type: :binary_id

    timestamp
end

@leogottardi
Copy link

Obrigado pela essência. Apenas para apontar, se você precisa criar uma referência para a chave estrangeira baseada em uuid, você vai querer usar referências ("tabela", digite:: uuid) em sua migração de referência, como este:

def change do
    alter table("comments") do
      add :post_id, references(:posts, type: :uuid)
    end
  end

E para o esquema

schema "comments" do
    field :body, :string
    belongs_to :post, MyBlog.Post, type: :binary_id

    timestamp
end

Thanks for pointing this out, it solved my problem :)

@schweigert
Copy link

@zjsherbondy you can set this:

 @foreign_key_type :binary_id

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment