Rails migration - Mysql2::Error: Specified key was too long; max key length is 767 bytes

Rails migration - Mysql2::Error: Specified key was too long; max key length is 767 bytes

我正在 Ruby Rails 项目上工作。

我正在使用 MySQL2 作为适配器。

这是 migrations 文件之一。

class CreatePages < ActiveRecord::Migration[6.0]
  def change
    create_table :pages do |t|
      t.string :base_url, null: false
      t.string :html, null: false
      t.string :styles, null: false
      t.text :images, null: false

      t.timestamps
    end

    add_index :pages, [:base_url, :html, :styles, :images], length: { images: 767 }, unique: true
  end
end
rake db:migrate

我遇到了这个错误。

Mysql2::Error: Specified key was too long; max key length is 767 bytes
/home/ubuntu/project/db/migrate/20200504001308_create_pages.rb:12:in `change'

Caused by:
ActiveRecord::StatementInvalid: Mysql2::Error: Specified key was too long; max key length is 767 bytes
/home/ubuntu/project/db/migrate/20200504001308_create_pages.rb:12:in `change'

Caused by:
Mysql2::Error: Specified key was too long; max key length is 767 bytes
/home/ubuntu/project/db/migrate/20200504001308_create_pages.rb:12:in `change'

谁能帮帮我?

根据您的 table 编码,某些字符集的每个字符可以使用多个字节。 MySQL 中的 utf8 编码需要每个字符 3 个字节,因此对于此编码 (767 / 3),字符串限制应为 255。如果编码为 utf8mb4,每个字符需要 4 个字节,则应将限制设置为 191 (767 / 4)。

因此您的迁移文件可能如下所示:

class CreatePages < ActiveRecord::Migration[6.0]
  def change
    create_table :pages do |t|
      t.string :base_url, limit: 191, null: false
      t.string :html, limit: 191, null: false
      t.string :styles, limit: 191, null: false

      # etc ...
    end
  end
end

这似乎是旧 MySQL 版本的限制,这就是为什么默认 Rails doesn't handle this 大小写的原因。