简体   繁体   中英

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

I tried to run migration, however, I get this error:

ActiveRecord::StatementInvalid: Mysql2::Error: Specified key was too long; max key length is 767 bytes: CREATE TABLE `user_mobile_tokens` (`id` int AUTO_INCREMENT PRIMARY KEY, `contractor_id` int, `endpoint_arn` text, `token` text, `platform` varchar(255), `subscription_arn` text, `user_type` varchar(255), `user_id` int, `created_at` datetime NOT NULL, `updated_at` datetime NOT NULL,  INDEX `index_user_mobile_tokens_on_contractor_id`  (`contractor_id`),  INDEX `index_user_mobile_tokens_on_user_type_and_user_id`  (`user_type`, `user_id`), CONSTRAINT `fk_rails_beefd2cf74`
FOREIGN KEY (`contractor_id`)
  REFERENCES `contractors` (`id`)
) ENGINE=InnoDB

my migration is:

class CreateUserMobileToken < ActiveRecord::Migration[5.0]
  def change
    create_table :user_mobile_tokens do |t|

      t.references :contractor, foreign_key: true
      t.text :endpoint_arn
      t.text :token
      t.string :platform

      t.text :subscription_arn

      t.references :user, polymorphic: true
      t.timestamps
    end
  end
end

I suspected the foreign key t.references :contractor , I tried to add , type: :integer as:

t.references :contractor, foreign_key: true, type: :integer

but I got the same error, I am out of ideas about it..

I have solved the issue by manually creating the foreign keys, I also, added a limit for user_type for only 20 characters as needed, as it was the default size 255 characters, which is more than 767 bytes as the error was about.

class CreateUserMobileToken < ActiveRecord::Migration[5.0]
  def change
    create_table :user_mobile_tokens do |t|

      t.integer :contractor_id
      t.text :endpoint_arn
      t.text :token
      t.string :platform

      t.text :subscription_arn


      t.string :user_type, :limit => 20
      t.integer :user_id
      t.timestamps
    end

    add_index :user_mobile_tokens, [:user_id, :user_type]
    add_index :user_mobile_tokens, :contractor_id
  end
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM