ActiveRecord enum behaviour change in rails 6.1.4

Viewed 224

I am in the process of upgrading from 6.0.3 to 6.1.4. Once thing I noticed after the upgrade is that, enum attributes are no longer returning the keys. Its returning the actual value in the database.

eg:

  enum onboard_variation: {
    key1: "value1",
    key2: "value2",
    key3: "value3"
  }

In the console

Rails 6.0.3

Account.first.onboard_variation => "key1"

Rails 6.1.4

Account.first.onboard_variation => "value1"

I went through the entire release notes and there is not mention of this change. What could be contributing to this?

2 Answers

Figured out what the problem was. We had a custom default definition like below

attribute :onboard_variation, :string, default: -> { Utilities::Random.flip_coin ? "value1" : "value2" }

Rails 6.1 supports defaults on the enum definition. Changed to below and everything works as expected

enum onboard_variation: {
        key1: "value1",
        key2: "value2",
        key3: "value3"
      }, _default: -> { Utilities::Random.flip_coin ? "value1" : "value2" }

I found that issue is, when you define default enum value using attribute.

  enum status: {
    created: 0,
    proceed: 1
  }

  attribute :status, :integer, default: :created

to

  enum status: {
    created: 0,
    proceed: 1
  }, _default: "created"

  # remove attribute
Related