[Fixed] How can I fix "Unknown enum attribute" after Rails 7.1 upgrade? – Ruby-on-rails

by
Alexei Petrov
concurrent-ruby enums ruby-on-rails ruby-on-rails-7

The Problem:

After upgrading to Rails 7.1, an existing model with enum attributes generates the error "Unknown enum attribute" during migrations. The error message lacks specific details about the problematic enum attribute, making it difficult to identify and fix the issue. How can this be resolved?

The Solutions:

Solution 1: Use the `7-1-stable` branch and add an attribute for the enum

If you have enums that are not backed by a database column, you can use the 7-1-stable branch in Rails and add an attribute for the enum to fix the "Unknown enum attribute" error.

gem 'rails', git: 'https://github.com/rails/rails.git', branch: '7-1-stable'
class Company < ApplicationRecord
  attribute :auth_type, :string
  enum auth_type: {
    password: 'password',
    magic_link: 'magic_link',
    google: 'google',
    microsoft: 'microsoft',
    saml: 'saml',
    workos: 'workos',
    developer: 'developer'
  }, _prefix: :auth_by
end

Solution 2: Add a database column for the enum

If you want to use a database column for the enum, you can add it using a migration:
“`ruby
class AddMissingEnumsColumns < ActiveRecord::Migration[7.1] def change add_column :companies, :auth_type, :string end end ```

Solution 2: No direct model usage inside migrations

The error, “Unknown enum attribute ‘auth_type’ for Company,” is caused by using the model directly inside of a migration. This can happen when you have logic like `Company.where().find_each` inside an earlier migration file that is before the migration that added the `auth_type` column. As a result, the model tries to initialize the enum types before the column exists.

To fix this issue, remove the direct model usage inside of the migration. This will prevent the model from trying to initialize the enum types before the column exists. If you need to use the model inside of a migration, find a way to do so without using the model directly. This will enforce the enum logic.

Q&A

How can I fix "Unknown enum attribute" after Rails 7.1 upgrade?

Ensure you added columns representing your enums in the database before querying for them.

What is the reason for the error "Unknown enum attribute" after Rails 7.1 upgrade?

Rails 7.1 no longer supports enums without being backed by a DB column.

Video Explanation:

The following video, titled "Zipper Repair What can be fixed How to Fix my Zipper - YouTube", provides additional insights and in-depth exploration related to the topics discussed in this post.

Play video

Jeff is sharing his zipper knowledge with us! Do it yourself methods for zipper repair. Metal Teeth, Coil Teeth, ...