【问题标题】:Why do i keep getting an error when running rake db:migrate on my fresh rails instance?为什么在我的新 Rails 实例上运行 rake db:migrate 时总是出现错误?
【发布时间】:2013-06-11 14:20:16
【问题描述】:

为什么我在运行rake db:migrate时总是收到下面的错误...

我已经按照设计 github 自述文件中的 https://github.com/plataformatec/devise#getting-started 字母创建了一个全新的项目,但仍然出现错误。

创建了一个新的铁路应用:(成功

gem 'devise' 添加到我的 Gemfile:(成功

安装包:(成功

运行 rails 生成器:(成功

生成了一个名为 User 的设计模型:(成功

我在SQLite3:CantOpenException (uanble to open database file) 提到了 SO 问题,这导致我尝试使用返回db/development.sqlite3 already existsrake db:create。很好。

然后我按照入门运行 rake db:migrate..:(失败
带有错误SQLite3::CantOpenException: unable to open database file: CREATE UNIQUE INDEX "index_users_on_email" ON "users" ("email")/cygdrive/c/users/daniel/workspace/ruby/rails/tesT_app/db/migrate/20130606041329_devise_create_users.rb:40:inchange'`

发生了什么?我一直在关注这封信,但无法弄清楚!

非常感谢。

编辑:...create_users.rb 上的第 40 行是
add_index :users, :email, :unique => true

请注意我没有碰任何东西。

【问题讨论】:

  • 它适用于标准的 rails 对象,但只会抱怨 devise.. 不知道烫发是否会成为问题? edit 烫发很好
  • 你能发一份你的迁移文件吗?

标签: ruby ruby-on-rails-3 devise


【解决方案1】:

在 SQLite 中,索引名称的唯一性在数据库级别强制执行。在 MySQL 中,您不会重现相同的问题。您可以更改索引名称或注释掉这一行(并在生产中部署时返回),或更改数据库(我的意思是改用 mysql)。

【讨论】:

  • 谢谢 Ivan,我没有用 sqlite 做太多事情,所以我的无知可能会成为我最好的。如果你说的是真的,那为什么它不起作用是有道理的。我到家后会告诉你的
  • 所以——当我注释掉索引时它工作得很好——而且工作得很好。您能否将使您所说的内容正确的文档链接给我?链接我,上面写着“sqlite 使用强制索引”等。我真的很感激 :)
【解决方案2】:

抱歉,我以为你有一个单独的用户模型。 能否请您发布您的迁移文件? 也请尝试运行

rake db:drop

(删除您当前的数据库)然后

rake db:create and rake db:migrate

这将确保您正在迁移到全新的数据库。

【讨论】:

  • 感谢您的回答 - 我今天回家后会尝试这个
【解决方案3】:

我有类似的问题,我建议按照这种方式。分两步进行迁移:例如,假设您有一个名为 users 的迁移。像你一样正常迁移它,但这里还没有强制唯一性:

class CreateUsers < ActiveRecord::Migration
  def change
    create table :users do |t|
      t.integer :name
      t.integer :email
      t.timestamps
    end
  end
end

使用迁移:

$ bundle exec rake db:migrate

迁移后,创建另一个迁移:

$ rails generate migration add_index_users_name_email

在这个迁移文件中,添加唯一性:

class AddIndexUsersNameEmail < ActiveRecord::Migration
  def change
    add_index :users, :name, unique: true
    add_index :users, :email, unique: true
  end
end

像往常一样迁移,这应该可以工作并且不会抛出错误,因为正如 Ivan 提到的,SQLite 在 db 级别强制执行唯一性,以这种方式执行此操作将解决问题。

如果仍然抛出错误,另一种解决方法是为每个条目创建单独的迁移。例如:

$ rails generate migration add_index_users_name
$ rails generate migration add_index_users_email

class AddIndexUsersName < ActiveRecord::Migration
  def change
    add_index :users, :name, unique: true
  end
end

class AddIndexUsersEmail < ActiveRecord::Migration
  def change
    add_index :users, :email, unique: true
  end
end

如果它解决了你的问题,请告诉我

【讨论】:

    猜你喜欢
    • 2012-11-23
    • 2014-01-31
    • 2012-08-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多