rails: Rails 7.1 - can't define enums for attributes which don't exist in table

Not sure if this is an intended change or not. Pre 7.1, I could define an attr on a model using attribute and define enum values for it, then use enum helper methods. I’m using this heavily in my current project for i18ns etc, so defining the enum values as an array and manually validating won’t cover all my use cases

Since 7.1, this isn’t possible.

Steps to reproduce

# frozen_string_literal: true

require "bundler/inline"

gemfile(true) do
  source "https://rubygems.org"

  git_source(:github) { |repo| "https://github.com/#{repo}.git" }

  gem "rails", github: "rails/rails", branch: "main"
  gem "sqlite3"
end

require "active_record"
require "minitest/autorun"
require "logger"

# This connection will do for database-independent bug reports.
ActiveRecord::Base.establish_connection(adapter: "sqlite3", database: ":memory:")
ActiveRecord::Base.logger = Logger.new(STDOUT)

ActiveRecord::Schema.define do
  create_table :posts, force: true do |t|
  end
end

class Post < ActiveRecord::Base
  attribute :topic
  enum topic: %i[sports politics entertainment]
end

class BugTest < Minitest::Test
  def test_association_stuff
    post = Post.create!
    post.assign_attributes(topic: :sports)

    assert_equal true, post.sports?
  end
end# frozen_string_literal: true


Expected behavior

Post should instantiate correctly and can use enum helper methods

Actual behavior

Error thrown

RuntimeError: Unknown enum attribute 'topic' for Post

System configuration

Rails version: 7.1.1

Ruby version: ruby 3.1.2p20

About this issue

  • Original URL
  • State: closed
  • Created 3 years ago
  • Comments: 54 (16 by maintainers)

Commits related to this issue

Most upvoted comments

@byroot Is it possible you might have some kind of solution to resolve this error? I really don’t like the idea to edit old migrations.

You probably won’t like my answer but:

  • Accessing models in migration is an anti-pattern precisely because it introduce this kind of issues.
  • There is absolutely no reason to run 3 years old migrations. Use db:schema:load to directly start from a recent state.

Old migrations are meant to be deleted.

@byroot Not sure I’m in support of the absolutism here. 3 year old migrations could be run for any number of reasons, and the fact that we’re having this conversation is proof of that. As part of a major overhaul, I also would like to be able to run migrations from scratch and ensure they run correctly without having to rewrite them all. People do more than just migrate schema in migrations, and as far as I’m aware it’s a properly-supported use case for Rails Migrations (and precisely why everyone finds them so wonderful).

The main fact is that this worked before, and now it doesn’t, and your suggestion to (I think) go to SQL statements instead of using query abstractions seems a little counter-productive. One of the main points of migrations is to abstract database dialects, so I’m not sure peppering them with complex dialect-specific updates is a step in the right direction.

I am facing this same issue when the model is used in some migration before the enum is introduced for example

# app/models/user.rb
class User < ApplicationEnhancedVersionedRecord
  enum status: { draft: 'draft', published: 'published' }, _default: :draft
end

# 20220101000000_add_posts
class AddPosts < ActiveRecord::Migration[7.0]
  def change
    create_table :posts, id: :uuid do |t|
      t.string   :title, null: false
    end
  end
end

# 20220102000000_some_data_migration
class AddStatusToPosts < ActiveRecord::Migration[7.0]
  def change
    Post.find_each {...}
  end
end

# 20220103000000_add_status_to_posts
class AddStatusToPosts < ActiveRecord::Migration[7.0]
  def change
    add_column :posts, :status, :string, default: "draft"
  end
end

Now I get

StandardError: An error has occurred, this and all later migrations canceled: (StandardError)

Unknown enum attribute 'status' for Post

We have also encountered this issue, but in a slightly different way. We have a model where we added an enum column to it in a migration created long after the original table. This now creates the problem where we cannot run our migrations for an empty database, as the model defines the enum, but the column backing it doesn’t exist in the DB, and won’t until the migration is run which creates it.

We’ve hacked around it by defining an empty AR model for the table in the migrations which break, but this seems inelegant to say the least.

@zacheryph let me say this simply. this problem has nothing to do with model dependencies in the migration.

  1. add a table with create_table in a migration. dont run migration yet.
  2. in a second migration, add a column backing a rails enum, along with a concern that defines said enum.
  3. rails db:migrate will now throw an exception when running first migration.

I have issue similar to the one @jasonl has. There is an 3 years old migration in my app, which adds a column to User database table, and it populates it in the loop for each user:

def up
    add_column :users, :new_filled_column, :string

    User.find_each do |user|
      user.update(new_filled_column: User.default_field_value)
    end
  end

A year later another migration adds new column for storing enum value

add_column :users, :another_enum_column, :integer

and corresponding code to set its values

enum another_enum_column: { value_one: 1, value_two: 2 }, _prefix: true

So now when I reset my schema, I get an error: “Unknown enum attribute 'another_enum_column' for User”, because column another_enum_column doesn’t yet exist when older migration calls User model.

@byroot Is it possible you might have some kind of solution to resolve this error? I really don’t like the idea to edit old migrations.

In several of my project’s models, we define enum’s whose values are used to populate a character varying column (we are using Postgres). An example enum is below:

    enum order_by_types: {
      email: 'email',
      fax: 'fax',
      phone: 'phone',
      website: 'website'
    }

Before Rails 7.1, referencing and using enum’s like order_by_types above did not raise any errors. With Rails 7.1, tests are now failing with errors like the following:

     RuntimeError:
       Unknown enum attribute 'order_by_types' for Deals::Judgment

What I am looking for is some guidance on how best to fix this. It appears that we can no longer define enum’s inside models without a corresponding database table column.

Yes, that was intentional. See related issue https://github.com/rails/rails/issues/45668 for the discussion of the problem.

cc @byroot

@zacheryph let me say this simply. this problem has nothing to do with model dependencies in the migration.

To re-iterate on what @gsar posted - it’s not longer possible to add column and matching enum definition in single PR/change. Application won’t boot (model file won’t load) to perform the migration if the enum is defined and the column is not there. After this change, adding new column with enum definition requires two separate deployments.

While separating schema changes from code changes might be a good practice in many cases, there are as many cases when this complicates the flow and prevents fast iterations. This behavior is quite hard to detect early as well. Most developers will iterate in steps: adding columns, then adding enum and most of default pipelines won’t be able to detect this change (as the schema is loaded from the schema file on CI servers).

I don’t have a good idea/solution for this issue. Just wanted to make sure that this consequence of the change is clearly stated. 😅

@jasonl @arcreative

Referencing application models in migrations is an anti-pattern. There are reasons for this. For one, you cannot rely on their definition. You have any number of things that will break older migrations; Newer associations will fail old migrations for non-presence for instance. I’ve broke these kinds of migrations a week after they’re created simply by making a column not-null and adding a validates presence: true.

As well, you simply cannot rely on their existence. It is not uncommon to rename or even remove a model. Its not completely unfathomable for instance to rename your User model to say Person? Post to Article?

When I need (want) a model in a migration, I define one in the migration class that is specific for that migration, with just enough implementation for that migration to succeed. It may not look the best at first but I’ve simply just made this common practice, and you worry about old migrations failing a lot less. I personally find this cleaner as your migration is then completely self contained.

Agree that this is weird and regressive from my perspective. In our case, we have deploy scripts which are rake tasks that load the Rails env and are set to run before the database migration. These now will crash unless we split the DB changes out which is not a good developer experience, imo. Hoping for a workaround 🤞

I don’t follow. You say:

we define enum’s whose values are used to populate a character varying column

And then:

we can no longer define enum’s inside models without a corresponding database table column.

So first you say the enum is backed by a column, then you say it’s not. It’s really confusing.

I did so a couple of times in my life, but rather as a hack. I believe this is not the right way to go, not to become a standard approach at least. The case with #update_all was just an example, sometimes we need to pull more business logic. In my current project, started almost 10 years ago, around 50 database migrations are failing because of this.

I can also easily see this happening in other situations, e.g. when merging multiple pull-requests, when one adds a migration with data changes and another adds an enum. Where migrations worked alone and will stop working once merged.

I’m pretty much sure this error should have never existed. Honestly, this is none of the framework’s business what I do, when, and why. The error could happen when attempting to save the data or using the unum, but not in the runtime during boot. If there is any logic behind that error, that makes it impossible to define an enum without a corresponding column, then this is a regression in comparison with Rails 7 and below, where this was perfectly possible.

In other words, it is just bad design.

We are encountering same issue when upgrading an existing application, we have exact named column as well as exact named enum, but when i run rails db:create db:migrate it fails, because we try to use a such model in initializers for something, and when initializing, it seemingly breaks. So it i really really annoying and definately worth fixing.

@johan-smits what i have resorted to is to precede every enum declaration with an attribute line that declares the enum’s type. seems to be enough so far, and i havent had to change any migrations. see my note above

maybe the boilerplate docs for creating enums needs to include this?

@johan-smits change def change to def up and use execute “UPDATE accounts SET eula = FALSE”.

That said, I think we are all still unhappy about this surprising breaking change despite there being a solution for your particular use case. We shouldn’t have to rewrite all of our migrations (which span many versions!) for what feels like no good reason.

In my case I do use the anti-pattern but differently:

class AcceptAllAccountsEula < ActiveRecord::Migration[4.2]
  def change
    Account.update_all(eula: false)
  end
end

Since this only generates a single query directly into the database, this also fails for the same reason. But it never touches our uses the enum field.

The reason why we keep old migrations in the code and not drop them is that we have customer sites that need to upgrade and thet are not always on the same speed as we are.

Since this is anti-pattern what is then the suggested way to do such migrations with Rails?

  • There is absolutely no reason to run 3 years old migrations. Use db:schema:load to directly start from a recent state.

Old migrations are meant to be deleted.

@byroot this problem affects 3 week old migrations the same as it does 3 year old migrations, so this is not really an answer to anything. i’m finding myself peppering my concerns with defensive cruft like this now. and note the migrations that fail (that are slightly older than the enum code addition) don’t have any model dependencies in them, just a simple create_table or similar, so adding an enum to existing code introduces these retroactive time bombs in migrations if you don’t have the cruft in the enum definition. would you rather document that all enums need to have this instead of fixing the problem?

model FooBar
    extend ActiveSupport::Concern
    respond_to?(:foo_bar) && included do
        enum foo_bar: {
            ...
        }
    end
end

EDIT: above doesn’t really work, since respond_to? can’t be used within the concern to check if the column exists at the point where the include happens. so the enum never gets defined as a result. the only workaround i’ve been able to find is to “declare” the type of the enum with attribute like this:

model FooBar
    extend ActiveSupport::Concern
    attribute :foo_bar, :integer
    enum foo_bar: {
        ...
    }
end

i would suggest rails should be inferring the type of the enum from the way it is defined, and perhaps also allow passing the type as an extra option if the inference can’t be done reliably in every case.

    enum foo_bar: { ... }, _type: :integer

@jfloff Can you open a new issue with a minimal reproduction script based on https://github.com/rails/rails/blob/main/guides/bug_report_templates/active_record_gem.rb?

I am getting this error while including an enum through a concern.

In my concern (IdVerifiable) I have: enum id_verification_status: { ... } and then, this concern is included in my User model. But when I’m running my specs, it throws an error:

Undeclared attribute type for enum ‘id_verification_status’. Enums must be backed by a database column or declared with an explicit type via attribute.

Even through the user model, does have a column named id_verification_status. Here is the snippet from my schema.rb:

create_table "users", id: :serial, force: :cascade do |t|
    t.integer "id_verification_status", default: 0

Am I doing anything wrong here?

Changing the enum name to match the corresponding column name is fixing things for me. Again…my apologies for the confusion/noise in this thread.

If you’re referencing a class in the migration, mock it out in the same migration… see my SO answer at https://stackoverflow.com/questions/77260392/how-can-i-fix-unknown-enum-attribute-after-rails-7-1-upgrade/78041224#78041224

Basically you should be doing something like this…

class AddOnboardedToUser < ActiveRecord::Migration
  class User < ApplicationRecord
    attribute :status, :string
  end

  def change
    add_column :users, :onboarded, :boolean, null: false, default: fasle

    up_only do
      User.unscoped.update_all(onboarded: true)
    end
  end
end

It’s not an ideal situation/solution, but it gets the job done.

@zzak hi, no problem, sorry for overreacting. I thought that I’d tell I’m updating data from there, then you’d tell me that’s not the right place to do so, and we’d derail the conversation nowhere.

I know it is not the best place to do data migration, but I don’t agree it is the wrong place to do so. Sometimes you need to update the data within the migration transaction, so if anything goes wrong, then everything is rolled back.

But you don’t necessarily need to update the data, it is enough to just preload the model class in there.

Here is an example that should showcase the issue better

class User < ApplicationRecord
  enum :status, %w[pending approved]
end

class AddOnboardedToUser < ActiveRecord::Migration
  def change
    add_column :users, :onboarded, :boolean, null: false, default: fasle

    up_only do
      User.unscoped.update_all(onboarded: true)
    end
  end
end

class AddStatusToUser < ActiveRecord::Migration
  def change
    add_column :users, :status, :integer
  end
end

You can see two database migrations here, and if the first one was created and executed a long time ago, before the status enum was added into the User model, everything will be just fine. But if you then decide to do rake db:migrate:reset (e.g. to rebuild the test database), the first migration will fail, because the enum is already in the model but there is no corresponding column just yet, it was about to be added in the next migration.

@zzak I would like to highlight that the problem isn’t me doing something that doesn’t match someone’s preferences or expectations. The actual issue is that the framework fails to load its own components from within the database migration. Most likely because someone has simply forgotten about such a possibility.

This change breaks all migrations that invoke anything on models that have enums, columns for which were added in further migrations which were not invoked just yet.

Like others, we have encountered this issue with historic migrations. We also use the data-migrate gem to separate our schema and data migrations which helps for the most part, but the issue still arises if you call those data migrations.

We’d prefer not to remove/comment out previous data migrations if we can help it so instead decided to capture the error so that the data migrations continue as expected.

def up
  data_migration_code
rescue RuntimeError => e
  puts "Error Captured: #{e.full_message}"
end

@vpereira Thanks for the suggestion, I ended up cleaning up all my old migrations, and used squasher squasher 2024 --migration=7.0 to squash my old migrations before 2024(i wanted to do it anyway, to reduce db:migrate time).

Since this is anti-pattern what is then the suggested way to do such migrations with Rails?

We encountered a similar issue. Our CI runs rails db:migrate specifically to ensure we don’t leave any broken migration code lying around. One potential solution is to decouple data migration from schema migration using the data-migrate gem. It would be ideal to have an official “Rails way” to address this problem.

@johan-smits If I’m understanding correctly, this is what they’re suggesting as the correct way of doing it. I have a problem with it in that it forces us to leave the nice abstractions behind that Rails migrations/ActiveModel are meant to provide and instead couples us back to particular dialects, but they don’t seem to agree for whatever reason.

@zacheryph This is some serious hand-wavery, going to have to agree to disagree here. Not sure who defines patterns and anti-patterns, but as long as using classes in migrations is convenient and provides non-SQL abstractions, I would prefer to keep doing it.

  1. When adding a new, required association to a model, that association is going to fail whether you use the model class in the migration or not. I’m not sure what this is supposed to highlight, exactly. If your presence: true has a corresponding null: false as it should probably have at the database level, it would have failed already in the database layer.
  2. I would expect when you change a model name that you refactor your migrations, just like everything else. It’s not any different than replacing any other usage in your codebase.
  3. While creating a temporary model in your migration might have solved the problem for you, having done so with an enum that you considered “just enough implementation” would have broken just the same as it did for us, because they moved the goalposts with the enum class method. I still don’t see how your approach fixes anything.

Perhaps I’m not understanding the why of this change–I may have missed it here, but is there rationale/a PR for what was accomplished with this breaking change?

it looks like it may be a simple case of order_by_types not matching the order_by_type column name

If that’s so, then that’s exactly why we made this change. To catch these typos.