Skip to content
Ecto extension to support enums in models
Elixir
Latest commit 2aea7e7 May 11, 2016 @gjaldon use newer ex_doc
Failed to load latest commit information.
config
lib allow defenum/2 to accept variables May 11, 2016
test allow defenum/2 to accept variables May 10, 2016
.gitignore Docs generation Jul 7, 2015
LICENSE Initial commit Jul 7, 2015
README.md add step for adding to deps in README May 11, 2016
mix.exs
mix.lock use newer ex_doc May 11, 2016

README.md

EctoEnum

EctoEnum is an Ecto extension to support enums in your Ecto models.

Usage

First, we add ecto_enum to mix.exs:

def deps do
  [{:ecto_enum, "~> 0.3.0"}]
end

We will then have to define our enum. We can do this in a separate file since defining an enum is just defining a module. We do it like:

# lib/my_app/ecto_enums.ex

import EctoEnum
defenum StatusEnum, registered: 0, active: 1, inactive: 2, archived: 3

Once defined, EctoEnum can be used like any other Ecto.Type by passing it to a field in your model's schema block. For example:

defmodule User do
  use Ecto.Model

  schema "users" do
    field :status, StatusEnum
  end
end

In the above example, the :status will behave like an enum and will allow you to pass an integer, atom or string to it. This applies to saving the model, invoking Ecto.Changeset.cast/4, or performing a query on the status field. Let's do a few examples:

iex> user = Repo.insert!(%User{status: 0})
iex> Repo.get(User, user.id).status
:registered

iex> %{changes: changes} = cast(%User{}, %{"status" => "active"}, ~w(status), [])
iex> changes.status
:active

iex> from(u in User, where: u.status == :registered) |> Repo.all() |> length
1

Passing a value that the custom Enum type does not recognize will result in an error.

iex> Repo.insert!(%User{status: :none})
** (Elixir.EctoEnum.Error) :none is not a valid enum value

The enum type StatusEnum will also have a reflection function for inspecting the enum map in runtime.

iex> StatusEnum.__enum_map__()
[registered: 0, active: 1, inactive: 2, archived: 3]

Important links

Something went wrong with that request. Please try again.