Last active
September 7, 2016 07:46
-
-
Save websymphony/48dbfc8e663da8a0d63d to your computer and use it in GitHub Desktop.
Use UUIDs as primary key with Ecto - Phoenix Framework
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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