Techioz Blog

Rails 7.1 アップグレード後に「不明な列挙属性」を修正するにはどうすればよいですか?

概要

こんにちは。7.1 未満のレールで正常に動作する次の列挙型を備えたこの Company モデルがあります。

class Company < ApplicationRecord

  enum auth_type: {
    password: 'password',
    magic_link: 'magic_link',
    google: 'google',
    microsoft: 'microsoft',
    saml: 'saml',
    workos: 'workos',
    developer: 'developer'
  }, _prefix: :auth_by

end

Rails 7.1 にアップグレードしようとすると、CI 上の既存の移行が中断されるため、次のエラーが発生して動作が停止します。

Unknown enum attribute 'auth_type' for Company
/home/runner/work/clearyapp/clearyapp/vendor/bundle/ruby/3.2.0/gems/activerecord-7.1.0/lib/active_record/enum.rb:174:in `block in load_schema!'

このエラー発生は 7.1 で追加されたものでした https://my.diffend.io/gems/activerecord/7.0.8/7.1.0/page/26#d2h-285143-749

私が理解できないのは、エラーで有益な情報が何も得られない場合、どのように修正すればよいかということです。これは既知の enum 属性です =/

それを修正する方法を知っている人はいますか?

解決策

Rails 7.1 では列挙型の検証が追加され、DB 列にバックされない列挙型はサポートされなくなったようです。詳細については、この問題を確認してください。

@jonathanhefner は、DB に依存しない属性である列挙型のサポートを追加するこの PR を作成しました。 PRしたのは、

https://translate.google.com/translate?hl=ja&sl=en&tl=ja&u=https://github.com/rails/rails/pull/49769#issuecomment-1777833124

この問題に関しては 2 つのアプローチが考えられます。

7-1-stable ブランチを使用し、列挙型の属性を追加すると、エラーが解消されるはずです。

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
class AddMissingEnumsColumns < ActiveRecord::Migration[7.1]
  def change
    add_column :companies, :auth_type, :string
  end
end