RailsでDBにindexを貼る際のis too long the limit is 64 charactersの対処法

こんにちは!kossyです!




さて、今回はRailsでDBにindexを貼る際のis too long the limit is 64 charactersの対処法について、
ブログに残してみたいと思います。




環境
Ruby 2.6.3
Rails 6.0.3
MacOS Mojave



エラー詳細

まずエラーメッセージを記載します。

ArgumentError: Index name ‘index_user_joined_recture_subjects_on_user_next_recuture_facilities’ on table ‘user_joined_recture_subjects’ is too long; the limit is 64 characters

64文字以上のindex_nameを設定した場合、このエラーが発生します。

長いテーブル名 + 長いカラム名 の組み合わせになってしまうと、ハマってしまいますね、、、

次項で回避策について記載します。



回避するには

以下のように記述すれば回避できます。

add_index :user_joined_recture_subjects, :user_next_recuture_facilities, name: 'index_user_joined_recture_subjects_on_next_recture_faililities'

add_indexメソッドのnameオプションを用いることで、自由にindex_nameを定義できます。



勉強になりました。