【问题标题】:Provide text column length on composite unique index creation在创建复合唯一索引时提供文本列长度
【发布时间】:2018-05-11 14:57:54
【问题描述】:

我正在尝试在一个新表上创建一个索引,该索引需要agency_id(整数)和IP 地址(文本)的唯一性。我知道我需要为IP 提供索引长度。但是我在将长度分配给 just IP 列时遇到问题。

def up
   create_table :whitelisted_ips do |t|
     t.integer :agency_id
     t.text :ip
     t.timestamps
   end

   add_index :whitelisted_ips, [:agency_id, :ip], unique: true, length: 15
end

此代码返回错误

Mysql2::Error: 不正确的前缀键;使用的密钥部分不是字符串,使用的长度比密钥部分长,或者存储引擎不支持唯一前缀密钥: CREATE UNIQUE INDEX `index_whitelisted_ips_on_agency_id_and_ip` ON `whitelisted_ips` (`agency_id`(15), `ip`(15))

因为它试图将长度放在整数字段上。任何帮助将不胜感激。

【问题讨论】:

    标签: ruby-on-rails activerecord rails-activerecord composite-index


    【解决方案1】:

    您应该为 length 参数提供哈希值:

    add_index :whitelisted_ips, [:agency_id, :ip], unique: true, length: { ip: 15 }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-05-15
      • 1970-01-01
      • 1970-01-01
      • 2018-10-01
      • 2017-11-16
      • 1970-01-01
      • 2015-03-22
      • 1970-01-01
      相关资源
      最近更新 更多