【问题标题】:ActiveRecord::StatementInvalid: Could not find table 'users' Rails 5 tutorialActiveRecord::StatementInvalid: 找不到表'users' Rails 5 教程
【发布时间】:2019-12-12 11:12:48
【问题描述】:

在构建的示例应用程序 (Michael Hartl Rails 5) 上在 Rails 上运行测试,运行测试时出现上述错误,这表明它找不到表“用户”,它在我的 db 迁移文件夹中可用在 development.sqlite3 文件中列出,所以不确定是什么问题

尝试了运行 rake db:test:prepare、rails db:migrate:reset 测试的推荐修复程序,以查看 User.new(name: 'foo') 创建用户是否都没有解决问题,而后者在控制台所以无法理解为什么找不到表

_create_users.rb

  def change
    create_table :users do |t|
      t.string :name
      t.string :email

      t.timestamps
    end
  end
end

在尝试“rails test:mailers”时运行错误的测试,在使用“rails test”时会运行更多

db:migrate SQLite

【问题讨论】:

  • 在我生成以下内容之前正在工作:'rails generate migration add_reset_to_users reset_digest:stringreset_sent_at:datetime' 这造成了一个问题,我相信是因为缺少空间,所以我运行了这个:'rails generate migration add_reset_to_users reset_digest:string reset_sent_at:datetime' & 然后'rails generate migration add_reset_sent_at_to_users reset_sent_at:datetime' 修复了上一个问题,但现在测试不起作用
  • 你的“不工作”是什么意思,你能详细说明你的问题吗?
  • 当使用rails test:mailers 运行测试时,它会出现上述错误,并且其他帖子中建议的修复并没有解决问题:
  • ERROR["test_account_activation", UserMailerTest, 0.21548007300043537] test_account_activation#UserMailerTest (0.22s) ActiveRecord::StatementInvalid: ActiveRecord::StatementInvalid: 找不到表'users'

标签: ruby ruby-on-rails-5


【解决方案1】:

重要的是要记住 Rails 中的每个环境都有自己的数据库。仅仅因为您的应用程序在您进行开发时正在运行 (RAILS_ENV=development),并不意味着在运行测试时数据库就在那里 (RAILS_ENV=test)。

您可能只需要准备好您的测试数据库(创建并迁移它):

# Drop any test DB you already have
bundle exec rake db:drop RAILS_ENV=test

# Create a clean fresh one
bundle exec rake db:create RAILS_ENV=test

# Import the Schema from your schema.rb, rather than run all migrations
bundle exec rake db:schema:load RAILS_ENV=test

如果您执行上述操作然后运行测试,它们应该会按预期工作。

【讨论】:

  • 您好我已经尝试了上述方法,但仍然出现相同的错误。现在在开发网站上进行了测试,似乎用户表也不再存在,看不到它是如何被删除的
  • 用户表是否在您的schema.rb 中?也许您需要在您的开发环境中 rake db:migrate 才能正确地将其恢复到您的 schema.rb 中,然后我上面的命令可能会起作用?
  • 我发现架构中定义的问题,与上面的错字ActiveRecord::Schema.define(version: 20190804192901) do # Could not dump table "users" because of following StandardError # Unknown type 'stringreset_sent_at' for column 'reset_digest'有关,我之前错过了空间,但现在不知道如何纠正这个问题,也许我可以回滚数据库?跨度>
  • 如果您不需要担心生产数据,您可以简单地修复迁移,然后rake db:droprake db:createrake db:migrate
  • 谢谢,在我删除了我用错字制作的原始迁移文件后工作 - 已修复,我现在更了解迁移,干杯
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-10-13
  • 1970-01-01
  • 1970-01-01
  • 2013-10-31
  • 2013-09-06
  • 1970-01-01
相关资源
最近更新 更多