Rails creating schema_migrations - Mysql2::Error: Specified key was too long

不问归期 提交于 2019-12-04 05:06:40
dpa

767 key should work. Make sure you use utf8 encoding, and not utf16. I had same problem, and my mistake was that I accidently created utf16 database

I suggest you to drop your database and recreate a new one with the following instructions :

 mysql -u root -p -e "CREATE DATABASE {DB_NAME} DEFAULT CHARACTER SET utf8 DEFAULT COLLATE utf8_general_ci;"

I have the same problem with a column named version for varchar of length 2000

class AddVersionToUsers < ActiveRecord::Migration
  def change
    add_column :users, :version, :string, limit:2000
    add_index  :users, :version
  end
end

I was using this latin 1 1 character 1 byte, but now I want to use utf8mb4 1 character 4 bytes.

Configuring your databse like this you can get index until 3072 bytes:

docker run -p 3309:3306 --name test-mariadb -e MYSQL_ROOT_PASSWORD=Cal1mero. -d mariadb:10.2 --character-set-server=utf8mb4 --collation-server=utf8mb4_unicode_ci --innodb-large-prefix=1 --innodb-file-format=barracuda --innodb-file-per-table=1 --innodb-strict-mode=1 --innodb-default-row-format=dynamic

this is enough for latin_1, (will be 2000 bytes), but for utf8mb4 it will be 8000 bytes. In this keys you have some options

Add a column named hash_version and implement the index on that column.

Consistent String#hash based only on the string's content

Make the string shorter, it should work , but depernds on your needs

or use fulltext in your migrations, like this:

class AddVersionToUsers < ActiveRecord::Migration
  def change
    add_column :users, :version, :string, limit:2000
    add_index  :users, :version, type: :fulltext
  end
end

references:

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!