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
- Support non-column-backed attributes for enum Follow-up to #45734. This re-adds support for using `enum` with non-column-backed attributes while still guarding against typos in enum attribute names.... — committed to jonathanhefner/rails by jonathanhefner 3 years ago
- Revert "Merge pull request #49769 from jonathanhefner/active_record-enum-non-column-backed" This reverts commit 121e0ad015c74eaaca82c6c9a85f5b2e0672ca0b, reversing changes made to d68e43922bc11829c52... — committed to rails/rails by rafaelfranca 2 years ago
- Revert "Merge pull request #49769 from jonathanhefner/active_record-enum-non-column-backed" This reverts commit 121e0ad015c74eaaca82c6c9a85f5b2e0672ca0b, reversing changes made to d68e43922bc11829c52... — committed to rails/rails by rafaelfranca 2 years ago
- Revert "Merge pull request #49769 from jonathanhefner/active_record-enum-non-column-backed" This reverts commit 121e0ad015c74eaaca82c6c9a85f5b2e0672ca0b, reversing changes made to d68e43922bc11829c52... — committed to rails/rails by rafaelfranca 2 years ago
- Revert "Merge pull request #49769 from jonathanhefner/active_record-enum-non-column-backed" This reverts commit 121e0ad015c74eaaca82c6c9a85f5b2e0672ca0b, reversing changes made to d68e43922bc11829c52... — committed to DanielaVelasquez/rails by rafaelfranca 2 years ago
- Support non-column-backed attributes for enum Follow-up to #45734. This re-adds support for using `enum` with non-column-backed attributes while still guarding against typos in enum attribute names.... — committed to yoones/rails by jonathanhefner 3 years ago
You probably won’t like my answer but:
db:schema:loadto 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
Now I get
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.
create_tablein a migration. dont run migration yet.enum, along with a concern that defines saidenum.rails db:migratewill 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:
A year later another migration adds new column for storing enum value
and corresponding code to set its values
So now when I reset my schema, I get an error: “
Unknown enum attribute 'another_enum_column' for User”, because columnanother_enum_columndoesn’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 acharacter varyingcolumn (we are using Postgres). An exampleenumis below:Before Rails 7.1, referencing and using
enum’s likeorder_by_typesabove did not raise any errors. With Rails 7.1, tests are now failing with errors like the following: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
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
Usermodel to sayPerson?PosttoArticle?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:
And then:
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_allwas 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:migrateit 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
attributeline that declares the enum’s type. seems to be enough so far, and i havent had to change any migrations. see my note abovemaybe the boilerplate docs for creating enums needs to include this?
@johan-smits change
def changetodef upand useexecute “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-patternbut differently: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-patternwhat is then the suggested way to do such migrations with Rails?@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_tableor 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?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 theincludehappens. 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 withattributelike this: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.
@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 myUsermodel. But when I’m running my specs, it throws an error:Even through the user model, does have a column named
id_verification_status. Here is the snippet from my schema.rb:Am I doing anything wrong here?
Changing the
enumname 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…
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
You can see two database migrations here, and if the first one was created and executed a long time ago, before the
statusenum was added into theUsermodel, everything will be just fine. But if you then decide to dorake 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.
@vpereira Thanks for the suggestion, I ended up cleaning up all my old migrations, and used squasher
squasher 2024 --migration=7.0to squash my old migrations before 2024(i wanted to do it anyway, to reduce db:migrate time).We encountered a similar issue. Our CI runs
rails db:migratespecifically 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.
presence: truehas a correspondingnull: falseas it should probably have at the database level, it would have failed already in the database layer.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?
If that’s so, then that’s exactly why we made this change. To catch these typos.