ChatGPT解决这个技术问题 Extra ChatGPT

如何在 Ruby on Rails ActiveRecord 迁移中处理过长的索引名称?

我正在尝试添加一个从四个关联表的外键创建的唯一索引:

add_index :studies,
  ["user_id", "university_id", "subject_name_id", "subject_type_id"],
  :unique => true

数据库对索引名称的限制导致迁移失败。这是错误消息:

表 'studies' 上的索引名称 'index_studies_on_user_id_and_university_id_and_subject_name_id_and_subject_type_id' 太长;限制为 64 个字符

我该如何处理?我可以指定不同的索引名称吗?


R
Ri1a

add_index 提供 :name 选项,例如:

add_index :studies,
  ["user_id", "university_id", "subject_name_id", "subject_type_id"], 
  unique: true,
  name: 'my_index'

如果在 create_table 块中使用 references 上的 :index 选项,则它采用与 add_index 相同的选项哈希作为其值:

t.references :long_name, index: { name: :my_index }

根据 APIdock,名称必须是字符串,而不是符号
对于任何需要它的人来说,向下的语法是 remove_index :studies, :name => 'my_index'
On Rails 4.2.6index: { name: :my_index } 一起使用。只有 name 不起作用。
C
Craig Walker

您还可以更改 create_table 块内的列定义中的索引名称(例如从迁移生成器中获取)。

create_table :studies do |t|
  t.references :user, index: {:name => "index_my_shorter_name"}
end

请注意,这不会从原始问题创建多列索引;它只是演示如何从 create_table 缩短长索引名称
当我尝试在具有索引 t.references :searchable, polymorphic:true, index: {:name => "index_searches_on_searchable"} 的名称间隔表上创建多态引用时,这对我很有帮助,在这种情况下,索引实际上是一个多列(searchable_id 和 searchable_type),并且在生成的名称中添加了命名空间变得很长。
对我来说很好,紧凑的解决方案。谢谢!
还应该有 foreign_key: true,顺便说一句,这是一个很好的解决方案,因为当您使用 rails 生成器 model:references 格式创建迁移文件时,它是最容易使用的
P
Peter Mortensen

在 PostgreSQL 中,the default limit is 63 characters。因为索引名称必须是唯一的,所以有一点约定是很好的。我使用(我调整了示例以解释更复杂的结构):

def change
  add_index :studies, [:professor_id, :user_id], name: :idx_study_professor_user
end

正常的索引应该是:

:index_studies_on_professor_id_and_user_id

逻辑是:

索引变为 idx

单表名

没有连接词

没有_id

按字母顺序

这通常可以完成这项工作。


感谢分享。如果您可以链接 Postgres 文档以了解限制事实,那就太好了。
我们是否需要索引名称中的表名,因为索引无论如何都属于该表?只是好奇这是否对我没见过的地方有益。
您可以为索引命名您想要的名称,但我认为索引名称中的表名有助于保持索引名称的唯一性(这是强制性的),良好的范围并提高了一些错误消息的可读性。
P
Peter Mortensen

你也可以做

t.index([:branch_id, :party_id], unique: true, name: 'by_branch_party')

Ruby on Rails API


P
Peter Mortensen

与上一个答案类似:只需将 'name' 键与常规 add_index 行一起使用:

def change
  add_index :studies, :user_id, name: 'my_index'
end

w
whatapalaver

恐怕这些解决方案都不适合我。可能是因为我在 create_table 迁移中使用 belongs_to 进行多态关联。

我将在下面添加我的代码和一个对我有帮助的解决方案的链接,以防其他人在搜索与多态关联相关的“索引名称太长”时偶然发现。

以下代码对我不起作用:

def change
  create_table :item_references do |t|
    t.text :item_unique_id
    t.belongs_to :referenceable, polymorphic: true
    t.timestamps
  end
  add_index :item_references, [:referenceable_id, :referenceable_type], name: 'idx_item_refs'
end

这段代码对我有用:

def change
  create_table :item_references do |t|
    t.text :item_unique_id
    t.belongs_to :referenceable, polymorphic: true, index: { name: 'idx_item_refs' }

    t.timestamps
  end
end

这是帮助我的 SO Q&A:https://stackoverflow.com/a/30366460/3258059


J
Jerph

我有一个项目经常使用生成器并且需要它是自动的,所以我从 rails 源复制了 index_name 函数来覆盖它。我在 config/initializers/generated_index_name.rb 中添加了这个:

# make indexes shorter for postgres
require "active_record/connection_adapters/abstract/schema_statements"
module ActiveRecord
  module ConnectionAdapters # :nodoc:
    module SchemaStatements
      def index_name(table_name, options) #:nodoc:
        if Hash === options
          if options[:column]
            "ix_#{table_name}_on_#{Array(options[:column]) * '__'}".slice(0,63)
          elsif options[:name]
            options[:name]
          else
            raise ArgumentError, "You must specify the index name"
          end
        else
          index_name(table_name, index_name_options(options))
        end
      end
    end
  end
end

它会创建像 ix_assignments_on_case_id__project_id 这样的索引,如果它仍然太长,则将其截断为 63 个字符。如果表名很长,这仍然是不唯一的,但是您可以添加复杂性,例如将表名与列名分开缩短或实际检查唯一性。

请注意,这是来自 Rails 5.2 项目;如果您决定这样做,请从您的版本中复制源代码。


F
Fred Willmore

我遇到了这个问题,但是使用了 timestamps 函数。它在 updated_at 上自动生成超过 63 个字符限制的索引:

def change
  create_table :toooooooooo_loooooooooooooooooooooooooooooong do |t|
    t.timestamps
  end
end

表“toooooooooo_looooooooooooooooooooooooooooong”上的索引名称“index_toooooooooo_looooooooooooooooooooooooooooong_on_updated_at”太长;限制为 63 个字符

我尝试使用 timestamps 来指定索引名称:

def change
  create_table :toooooooooo_loooooooooooooooooooooooooooooong do |t|
    t.timestamps index: { name: 'too_loooooooooooooooooooooooooooooong_updated_at' }
  end
end

但是,这会尝试将索引名称同时应用于 updated_atcreated_at 字段:

表“toooooooooo_looooooooooooooooooooooooooooong”上的索引名称“too_long_updated_at”已存在

最后我放弃了 timestamps,只是创建了很长的时间戳:

def change
  create_table :toooooooooo_loooooooooooooooooooooooooooooong do |t|
    t.datetime :updated_at, index: { name: 'too_long_on_updated_at' }
    t.datetime :created_at, index: { name: 'too_long_on_created_at' }
  end
end

这可行,但我很想听听 timestamps 方法是否可行!


A
Adário Muatelembe

create_table :you_table_name 做 |t| t.references :studant, index: { name: 'name_for_studant_index' } t.references :teacher, index: { name: 'name_for_teacher_index' } end