LoginSignup
1
0

More than 1 year has passed since last update.

【Ruby on Rails】migration index too long なエラーを解決

Posted at

環境

  • Ruby 2.6.3
  • Ruby on Rails 6.0.1
  • PostgreSQL 10

発生状況

今回のエラーが起きたマイグレーションファイル

class CreateFooBarExampleRegistrations < ActiveRecord::Migration[6.0]
  def change
    create_table :foo_bar_example_registrations do |t|
      t.references :parent_example_table_name, null: false, foreign_key: true
      t.timestamps
    end
  end
end

長いテーブル名&カラム名に外部キー制約を設定しようとしていました。

エラー文

実行すると...

Index name 'index_foo_bar_example_registrations_on_parent_example_table_name_id'
 on table 'foo_bar_example_registrations' is too long; the limit is 63 characters`

どうやら63文字に収めないといけないようです。

 解決方法

作成するインデックス名を明示してあげる。

外部キーを設定する際にインデックス名を設定しないと、自動的にRailsが生成してくれます。
しかし、postgresで使う名前は63バイトに限定されている為、このエラーが発生します。

そこで↓のように変更を加えます。

class CreateFooBarExampleRegistrations < ActiveRecord::Migration[6.0]
  def change
    create_table :foo_bar_example_registrations do |t|
      t.references :parent_example_table_name, null: false, foreign_key: true,
                    index: { name: :index_foo_bar_regs_on_parent_example_table_name_id }
                    # ↑省略したインデックス名を設定してあげる。
      t.timestamps
    end
  end
end

名前の付け方

基本は
index_<テーブル名>_<外部キー制約を設定するカラム名>_id
というインデックスが張られるので、その規則に合わせて名前を短縮してあげると良いと思います。

1
0
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
0