ruby-on-railsenums

Rails 7.2.2 - Invalid input value for enum using positional arguments


I saw this warning and decided to fix it.

DEPRECATION WARNING: Defining enums with keyword arguments is deprecated and will be removed in Rails 8.0. Positional arguments should be used instead

Changed my enum as follows:

Before:

  enum budget: {
    below_100k: "below_100k",
    from_100k_to_250k: "from_100k_to_250k",
    from_250k_to_500k: "from_250k_to_500k",
    from_500k_to_1m: "from_500k_to_1m",
    from_1m_to_2500k: "from_1m_to_2500k",
    from_2500k_to_5m: "from_2500k_to_5m",
    from_5m_to_10m: "from_5m_to_10m",
    from_10m_to_20m: "from_10m_to_20m",
    from_20m_to_50m: "from_20m_to_50m",
    from_50m_to_100m: "from_50m_to_100m",
    from_100m_to_250m: "from_100m_to_250m",
    from_250m_to_500m: "from_250m_to_500m",
    from_500m_to_1b: "from_500m_to_1b",
    from_1b_to_2500m: "from_1b_to_2500m",
    from_2500m_to_5b: "from_2500m_to_5b",
    from_5b_to_10b: "from_5b_to_10b",
    above_10b: "above_10b",
  }

After:

  enum :budget, [
    :below_100k,
    :from_100k_to_250k,
    :from_250k_to_500k,
    :from_500k_to_1m,
    :from_1m_to_2500k,
    :from_2500k_to_5m,
    :from_5m_to_10m,
    :from_10m_to_20m,
    :from_20m_to_50m,
    :from_50m_to_100m,
    :from_100m_to_250m,
    :from_250m_to_500m,
    :from_500m_to_1b,
    :from_1b_to_2500m,
    :from_2500m_to_5b,
    :from_5b_to_10b,
    :above_10b
  ]

Then in rails console, I tried:

Organization.create!(budget: "below_100k", name: "r1")

The error:

invalid input value for enum organization_budget: "0"

Here is how the schema looks like:

    create_enum "organization_budget",
                [
                  "below_100k", "from_100k_to_250k", "from_250k_to_500k", "from_500k_to_1m", "from_1m_to_2500k",
                  "from_2500k_to_5m", "from_5m_to_10m", "from_10m_to_20m", "from_20m_to_50m", "from_50m_to_100m",
                  "from_100m_to_250m", "from_250m_to_500m", "from_500m_to_1b", "from_1b_to_2500m",
                  "from_2500m_to_5b", "from_5b_to_10b", "above_10b"
                ]

Here is the postgresql query:

SELECT enumlabel
FROM pg_enum
WHERE enumtypid = (
  SELECT oid FROM pg_type WHERE typname = 'organization_budget'
);
     enumlabel
-------------------
 below_100k
 from_100k_to_250k
 from_250k_to_500k
 from_500k_to_1m
 from_1m_to_2500k
 from_2500k_to_5m
 from_5m_to_10m
 from_10m_to_20m
 from_20m_to_50m
 from_50m_to_100m
 from_100m_to_250m
 from_250m_to_500m
 from_500m_to_1b
 from_1b_to_2500m
 from_2500m_to_5b
 from_5b_to_10b
 above_10b
(17 rows)

How do I fix this?

gem "rails", ">= 7.2.2"

Solution

  • This is calling enum with keyword arguments:

    enum symbol: { ... }
    #    ^^^^^^^keyword
    

    This is calling enum with positional arguments:

    enum :symbol, { ... }
    

    So you want switch to this:

    enum :budget, {
      below_100k: "below_100k",
      from_100k_to_250k: "from_100k_to_250k",
      ...
    }