Ecto: Ecto.Enum and schemaless changesets

Created on 25 Nov 2020  路  3Comments  路  Source: elixir-ecto/ecto

Environment

  • Elixir version (elixir -v): 1.11.2
  • Ecto version (mix deps): 3.5.5

Current behavior

It is not covered in docs. I tried this, but without success

iex> {%{}, %{p: {:parameterized, Ecto.Enum, %{values: [:a]}}}} |> cast(%{p: "a"}, [:p])  
#Ecto.Changeset<
  action: nil,
  changes: %{},
  errors: [
    p: {"is invalid",
     [type: {:parameterized, Ecto.Enum, %{values: [:a]}}, validation: :cast]}
  ],
  data: %{},
  valid?: false
>

Expected behavior

support this if possible and document how to use

Most helpful comment

Hvae you tried calling Ecto.Enum.init(...) when setting up the type instead of hardcoding the values directly?

All 3 comments

Hvae you tried calling Ecto.Enum.init(...) when setting up the type instead of hardcoding the values directly?

Ecto.Enum.cast relies on the on_dump option. It is defined based on the values option when initializing the field:

iex(9)> Ecto.Enum.init(values: [:a, :b, :c])
%{
  on_dump: %{a: "a", b: "b", c: "c"},
  on_load: %{"a" => :a, "b" => :b, "c" => :c},
  values: [:a, :b, :c]
}

So, I believe your example could be:

iex(11 > {%{}, %{p: {:parameterized, Ecto.Enum, Ecto.Enum.init(values: [:a]}}} |> Ecto.Changeset.cast(%{p: "a"}, [:p])   

Ah, thank you! Didn't know about init.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

jonasschmidt picture jonasschmidt  路  4Comments

jbence picture jbence  路  3Comments

brandonparsons picture brandonparsons  路  3Comments

nathanjohnson320 picture nathanjohnson320  路  4Comments

wojtekmach picture wojtekmach  路  3Comments