Enuma.Ecto (Enuma v0.1.0)
View SourceEcto type for Enuma Enums.
Using Enuma.Ecto with Ecto schemas
The Enuma.Ecto
type allows you to use Enuma enums in your Ecto schemas.
It supports two storage formats: :string
and :map
.
Basic Usage
To use an Enuma enum in your Ecto schema:
defmodule StatusEnum do
use Enuma
defenum do
item :active
item :inactive
end
end
defmodule MySchema do
use Ecto.Schema
schema "my_table" do
field :status, Enuma.Ecto, type: StatusEnum, ecto_type: :string
end
end
Storage Formats
String Format (:string
)
When using :string
as the ecto_type
, the enum will be stored as a string in the database.
This format only supports simple enum values (atoms without arguments).
field :status, Enuma.Ecto, type: StatusEnum, ecto_type: :string
With this configuration:
:pending
will be stored as"pending"
in the database- Complex enum values (tuples with arguments) are not supported and will result in an error
Map Format (:map
)
When using :map
as the ecto_type
, the enum will be stored as a JSON map in the database.
This format supports both simple enum values and complex enum values with arguments.
field :message, Enuma.Ecto, type: MessageEnum, ecto_type: :map
With this configuration items will be stored as maps with a "key"
and "values"
item.
Ecto Changesets
When working with changesets, you can use the enum values directly:
def changeset(schema, params) do
schema
|> cast(params, [:status])
|> validate_required([:status])
end
You can then pass enum values in your params:
MySchema.changeset(%MySchema{}, %{status: StatusEnum.active()})
# Or with complex values
MySchema.changeset(%MySchema{}, %{message: MyComplexEnum.move(1, 2)})
Summary
Functions
Callback implementation for Ecto.ParameterizedType.cast/2
.
Callback implementation for Ecto.ParameterizedType.dump/3
.
Callback implementation for Ecto.ParameterizedType.init/1
.
Callback implementation for Ecto.ParameterizedType.load/3
.
Callback implementation for Ecto.ParameterizedType.type/1
.
Functions
Callback implementation for Ecto.ParameterizedType.cast/2
.
Callback implementation for Ecto.ParameterizedType.dump/3
.
Callback implementation for Ecto.ParameterizedType.init/1
.
Callback implementation for Ecto.ParameterizedType.load/3
.
Callback implementation for Ecto.ParameterizedType.type/1
.