【问题标题】:How do I solve "index unique_schema_migrations already exists" in Rails?如何解决 Rails 中的“索引 unique_schema_migrations 已存在”?
【发布时间】:2008-10-14 16:15:29
【问题描述】:

运行 rake db:migrate 后跟 rake test:units 会产生以下结果:

rake test:functionals
(in /projects/my_project)
rake aborted!
SQLite3::SQLException: index unique_schema_migrations already exists: CREATE UNIQUE INDEX "unique_schema_migrations" ON "ts_schema_migrations" ("version")

db/schema.rb的相关部分如下:

create_table "ts_schema_migrations", :id => false, :force => true do |t|
  t.string "version", :null => false
end

add_index "ts_schema_migrations", ["version"], :name => "unique_schema_migrations", :unique => true

我不会在任何地方手动更改此索引,而是使用 Rails 的默认 SQLite3 适配器和全新的数据库。 (也就是说,在rake db:migrate 之前运行rm db/*sqlite3 没有帮助。)

test:units 任务是否可能试图重新加载架构?如果是这样,为什么?它不应该识别架构已经是最新的吗?

【问题讨论】:

  • schema.rb 中的 schema_migrations 表肯定没有其他索引声明。不过,有趣的是,该错误不会发生在 MySQL 上。
  • 这也可能与我使用table_name_prefix有关。在执行 rake db:schema:load 时,我得到了双前缀表。

标签: ruby-on-rails ruby migration


【解决方案1】:

在 SQLite 中,索引名称的唯一性在数据库级别强制执行。在 MySQL 中,唯一性仅在表级别强制执行。这就是为什么您的迁移在后者而不是前者中起作用的原因:您在不同的表上有两个同名的索引。

重命名索引,或找到并重命名另一个 unique_schema_migrations 索引,您的迁移应该可以工作。

【讨论】:

  • 我在 Laravel 中遇到了同样的问题,当测试开始迁移时,它说索引已经存在。我将所有索引更改为具有唯一名称(在表名之前)并且它有效。这是我认为的正确答案。
【解决方案2】:

在您的 database.yml 文件中,您的环境是否设置为连接到不同的数据库以进行开发和测试?

IE:

development:
  adapter: sqlite3
  database: db/dev.sqlite3
  timeout: 5000

test:
  adapter: sqlite3
  database: db/test.sqlite3
  timeout: 5000

【讨论】:

    【解决方案3】:

    尝试搜索您的 schema.rb 文件是否不包含创建同名索引的其他声明:unique_schema_migrations

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-11-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-25
      • 1970-01-01
      相关资源
      最近更新 更多