Help with Ecto.Enum fields and how to pass params into the changeset


I’m trying to use Ecto.Enum to store what days a given object is valid on. I have the following code:

defmodule Test do

  use Ecto.Schema

  import Ecto.Changeset

  schema "discount_code" do
    field(:days, Ecto.Enum, values: ~W(Monday Tuesday Wednesday Thursday Friday Saturday Sunday)a)

  def create(attrs) do
    changeset(%__MODULE__{}, attrs)

  def changeset(%__MODULE__{} = test, attrs) do
    |> cast(attrs, [:days])

I’ve tried various attributes to feed into the create function, including:

%{days: [:Monday :Tuesday :Wednesday]} |> Test.create()
%{days: ["Monday", "Tuesday", "Wednesday"]} |> Test.create()
%{days: "Monday, Tuesday, Wednesday"%} |> Test.create()

however when I try I get:

%{days: [:Monday]} |> Test.create()                          
  action: nil,
  changes: %{},
  errors: [
    days: {"is invalid",
       type: {:parameterized, Ecto.Enum,
          on_dump: %{
            Friday: "Friday",
            Monday: "Monday",
            Saturday: "Saturday",
            Sunday: "Sunday",
            Thursday: "Thursday",
            Tuesday: "Tuesday",
            Wednesday: "Wednesday"
          on_load: %{
            "Friday" => :Friday,
            "Monday" => :Monday,
            "Saturday" => :Saturday,
            "Sunday" => :Sunday,
            "Thursday" => :Thursday,
            "Tuesday" => :Tuesday,
            "Wednesday" => :Wednesday
          values: [:Monday, :Tuesday, :Wednesday, :Thursday, :Friday, :Saturday,
       validation: :cast
  data: #Test<>,
  valid?: false

What am I doing wrong? What format should these params be?

Thanks in advance

Ecto.Enum validates that the value is one of the available ones. The way it was intended to be used was this:

schema "discount_code" do
  field :day, Ecto.Enum, values: ~W(Monday Tuesday Wednesday Thursday Friday Saturday Sunday)a

%{day: :Monday} |> Test.create()

-.- thanks

You should be able to do the following if you need a list of values.

field :days, {:array, Ecto.Enum}, values: …
1 Like

Thanks, I was going to replace it completely but this looks like the best solution.

While I obviously didn’t know what an Enum is used for, I will say the error message could definitely have been a bit more informative.