Let's take advantage of Ecto.Enum and Ecto.Type.
The schema:
defmodule Blog.Category do
use Blog.Schema
schema "categories" do
field(:name, Ecto.Enum, [:til, :elixir, :ecto])
end
end
Divide & Conquer with Reflections and Ecto.Type.load/3:
iex> type = Blog.Category.__schema__(:type, :name)
{:parameterized, Ecto.Enum,
%{
mappings: [til: "til", elixir: "elixir", ecto: "ecto"],
on_cast: %{"til" => :til, "elixir" => :elixir, "ecto" => :ecto},
on_dump: %{til: "til", elixir: "elixir", ecto: "ecto"},
on_load: %{"til" => :til, "elixir" => :elixir, "ecto" => :ecto},
type: :string
}}
iex> Ecto.Type.load(type, "unknown")
:error
iex> Ecto.Type.load(type, "ecto")
{:ok, :ecto}
iex> Ecto.Type.load(type, :ecto)
:error
In the meantime:
iex> Ecto.Enum.values(Blog.Category, :name)
[:til, :elixir, :ecto]
iex> Ecto.Enum.dump_values(Blog.Category, :name)
["til", "elixir", "ecto"]
iex> Ecto.Enum.mappings(Blog.Category, :name)
[til: "til", elixir: "elixir", ecto: "ecto"]
Also, another great resource from German Velasco where he wrote Richer domain types with Ecto custom types
Happy Hacking!
Top comments (0)