elixir-ecto / ecto

A toolkit for data mapping and language integrated query.
https://hexdocs.pm/ecto
Apache License 2.0
6.19k stars 1.44k forks source link

Ecto.Enum and schemaless changesets #3493

Closed fuelen closed 3 years ago

fuelen commented 3 years ago

Environment

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

josevalim commented 3 years ago

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

v0idpwn commented 3 years ago

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])   
fuelen commented 3 years ago

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