LoginSignup
1
1

More than 1 year has passed since last update.

raise_conflict_error enumに定義できない命名について

Posted at

経緯

Ruby on Railsでアプリ作成中にenumでこのような定義し、rails c -sで動作確認をしたところエラーが発生しました。
今回の記事ではこのエラー発生原因と解決方法までを残します。同じプログラミング初心者へのヒントになれば幸いです。

model
class Present < ApplicationRecord
  with_options presence: true do
    validates :present_name
    validates :present_score
    validates :present_review
  end
      
  enum present_score: {
        poor: 1,
        average: 2,
        good: 3,
        verygood: 4,
        excellent: 5
    }
end

ターミナル
~~~省略~~~~
`raise_conflict_error': You tried to define an enum named "present_score" on the model "Present", but this will generate a class method "average", which is already defined by Active Record. (ArgumentError)

分析

  • エラー文を翻訳してみる
    raise_conflict_error
    Presentモデルpresent_scoreという名前の列挙型を定義しようとしたが,ActiveRecordによって既に定義されているクラスメソッドaverageが生成されます。 (ArgumentError)

分析結果

enumの定数名であるaverageが、既にActiveRecordによって既に定義されているクラスメソッドaverageをしようとしてしまうコンフリクトを起こしエラーとなっているようだ。
つまり予約語を定数名に定義したことがエラーの原因。

解決策

  • 命名規則に則った定数名に変更
model
class Present < ApplicationRecord
  with_options presence: true do
    validates :present_name
    validates :present_score
    validates :present_review
  end
      
  enum present_score: {
~~~~~~`下記修正`~~~~~~
        Very_Bad: 1,
        Bad: 2,
        Medium: 3,
        Good: 4,
        Very_Good: 5
~~~~~~`上記修正`~~~~~~
    }
end

rails c -sで動作確認し、無事にエラーなく動作できた。

以下参考資料

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1