【问题标题】:Mysql2::Error: Specified key was too long; max key length is 767 bytesMysql2::Error: 指定的键太长;最大密钥长度为 767 字节
【发布时间】:2019-07-28 15:18:42
【问题描述】:

我尝试运行迁移,但出现此错误:

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

我的迁移是:

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

我怀疑外键t.references :contractor,我尝试将, type: :integer添加为:

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

但我遇到了同样的错误,我对此一无所知..

【问题讨论】:

    标签: mysql ruby-on-rails ruby-on-rails-5


    【解决方案1】:

    我已经通过手动创建外键解决了这个问题,我还根据需要添加了 user_type 的限制,仅限 20 个字符,因为它是默认大小 255 个字符,错误超过 767 个字节大约。

    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
    

    【讨论】:

      猜你喜欢
      • 2013-11-25
      • 2016-04-15
      • 2012-05-31
      • 2015-06-22
      • 2019-05-26
      • 2013-12-21
      • 2015-06-29
      • 2016-10-04
      • 2014-08-17
      相关资源
      最近更新 更多