EctoPostgresEnum
Library which simplifies using PostgreSQL
enums
Installation
The package can be installed by adding ecto_postgres_enum
to your list of dependencies in mix.exs
:
def deps do
[
{:ecto_postgres_enum, "~> 1.0"}
]
end
Usage
To define enum simply use EctoPostgresEnum
module like:
defmodule MyEnum do
values = [:my, :enum]
use EctoPostgresEnum, values: values
end
# automatically generated type
MyEnum.type() == :my_enum
You can optionally define schema
and type
:
defmodule MyEnum do
values = [:my, :enum]
use EctoPostgresEnum, schema: :my_schema, type: :my_type, values: values
end
For more informations please take a look at EctoPostgresEnum
module.
After it add such enum to your schema like:
defmodule MySchema do
use Ecto.Schema
alias Ecto.Changeset
schema "my_table" do
field :my_field, MyEnum # add this
end
def changeset(my_element, my_params) do
Changeset.cast(my_element, my_params, [:my_field]) # cast as any other field
end
end
Finally you will also need to create migration like:
defmodule Example.Repo.Migrations.MyEnum do
use Ecto.Migration
def up do
MyEnum.create_db_enum()
alter table(:my_table) do
add :my_field, :my_enum # when automatically generated
# or
add :my_field, :my_type # when manually set
end
end
def down do
# Remember to remove all fields which are using your enum.
# Otherwise migration would fail!
alter table(:my_table) do
remove :my_field
end
MyEnum.drop_db_enum()
end
end