8

在我的 schema.rb 我有以下行:

add_index "users", ["email"], name: "index_users_on_email", unique: true, using: :btree

当我\di在 psql 中运行时,我得到:

Schema |                             Name                             | Type  | Owner |         Table
--------+--------------------------------------------------------------+-------+-------+-----------------------
 public | index_users_on_email                                         | index | alex  | users

但是,如果我在迁移中包含以下其中一项:

  • remove_index:用户,名称::index_users_on_email
  • 删除索引:用户,列::电子邮件
  • 删除索引:用户,:电子邮件
  • 执行'DROP INDEX index_users_on_email'

我收到以下错误:

rake aborted!
An error has occurred, this and all later migrations canceled:

Index name 'index_users_on_email' on table 'users' does not exist

我也发现了这个问题。那么有什么想法吗?

4

4 回答 4

11

我知道这来得太晚了,但我遇到了类似的事情。在尝试删除索引之前,您是否有机会重命名“电子邮件”列?如果是这样,通过重命名列,索引将被删除。所以顺序必须是:

1) 删除索引 2) 重命名列

于 2015-01-30T15:11:23.590 回答
8

如果要按名称删除索引,可以这样写:

remove_index(:table_name, :name => 'index_name')

您还应该看看这个问题:Rails 3.1.0 迁移中 remove_index 的正确语法是什么?

于 2013-10-22T15:17:33.570 回答
2

答案有点晚了,但我刚刚遇到了同样的问题,所以我写了这个答案,希望它能在未来帮助其他人。

原始提问者遇到的问题导致了解决方案。似乎在 Rails 3.x 中,的实现存在index_name_for_remove缺陷,因此有时它不接受命名索引。相反,它提出了一个ArgumentError声称该索引不存在的声明。

在 Rails 4.x 中,实现已更改,以便正确处理传递带有索引名称的哈希(我想,我目前没有 Rails 4 应用程序可供测试)。

如果您需要在 Rails 3.x 中处理此问题,请查看remove index解决方案的来源 - 使用该remove_index!方法。 remove_index!接受两个参数 - 表名和索引名。因此,对于原始发布者的问题,此命令应该可以完成工作:

remove_index! :users, :index_users_on_email

更新:发布答案后,我注意到原始发帖人询问的是 Rails 4,因此在某些情况下似乎仍然存在index_name_for_remove未检测到正确索引名称的问题。但是,由于索引的名称是已知的,并且我们不需要实际找出名称是什么(这是index_name_for_remove内部所做的),我们仍然可以使用该remove_index!方法将其删除。

于 2015-09-21T18:01:39.493 回答
0

我的错误:试图删除我正在删除的列上的索引。

迁移正在增加PG::UndefinedObject: ERROR: index "index_candidates_on_job_id_and_email" does not exist

class MergeJobAndJobCandidateModels < ActiveRecord::Migration[6.0]
  # ...
  def down
    change_table :candidates do |t|
      t.remove :job_id
      # ...
    end
    remove_index :candidates, %i[email job_id]
  end
end

错误:我正在删除列并试图删除索引。Rails/Postgres 将自动删除不再存在的列上的索引,因此我没有理由在迁移中删除此索引。

希望这可以为遇到此错误的其他人节省一点时间。

于 2020-06-16T17:47:53.893 回答