Skip to content

Rails 7.1 - can't define enums for attributes which don't exist in table #49717

@ejskipper

Description

@ejskipper

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

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions