Skip to content

Instantly share code, notes, and snippets.

@websymphony
Last active September 7, 2016 07:46
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save websymphony/48dbfc8e663da8a0d63d to your computer and use it in GitHub Desktop.
Save websymphony/48dbfc8e663da8a0d63d to your computer and use it in GitHub Desktop.
Use UUIDs as primary key with Ecto - Phoenix Framework
defmodule Blog.Repo.Migrations.CreatePost do
use Ecto.Migration
def up do
create table(:posts, primary_key: false) do
add :id, :uuid, primary_key: true
add :title, :string
add :body, :text
timestamps
end
end
def down do
drop table(:posts)
end
end
defmodule Blog.Post do
use Blog.Web, :model
# :binary_id is managed by drivers/adapters, it will be UUID for mysql
# but can be ObjectID if later you decide to use mongo
@primary_key {:id, :binary_id, autogenerate: true}
schema "posts" do
field :title, :string
field :body, :string
timestamps
end
@required_fields ~w(title body)
@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 \\ :empty) do
model
|> cast(params, @required_fields, @optional_fields)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment