Skip to content

Instantly share code, notes, and snippets.

@mreishus
Forked from stevedomin/create_post.exs
Created September 12, 2019 01:48
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mreishus/66cfb1d4262a7947db818cae3fd6c38d to your computer and use it in GitHub Desktop.
Save mreishus/66cfb1d4262a7947db818cae3fd6c38d 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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment