数据库的自定义耙任务:找不到表 [英] Custom rake task for DB: Table not found

查看:54
本文介绍了数据库的自定义耙任务:找不到表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个自定义的 rake 任务,它为各种情况创建一个包含数据的开发数据库.核心看起来像这样:

I have a custom rake task, that creates a development DB with data for various situation. The core looks like this:

namespace :db do
  task setup_seed: :environment do
    Rake::Task['db:drop'].invoke
    Rake::Task['db:create'].invoke
    Rake::Task['db:schema:load'].invoke
    Rake::Task['db:migrate'].invoke
    Rake::Task['db:test:prepare'].invoke
    Rake::Task['db:seed'].invoke
  end
end

一切运行正常,直到调用 db:seed,因为它会抛出表不存在的错误.这是我的seed.rb:

Everything runs fine, until db:seed is invoked, because it throws an error that tables does not exist. This is my seed.rb:

puts Rails.env
# => development
puts Article.count
# rake aborted!
# Mysql2::Error: Table 'app_test.articles' doesn't exist: SHOW FULL FIELDS FROM `articles`
# /usr/src/app/db/seeds.rb:2:in `<top (required)>'
# /usr/src/app/Rakefile:16:in `block (2 levels) in <top (required)>'
# Tasks: TOP => db:seed

我在这里注意到两件奇怪的事情:

I noticed two strange things here:

  • 首先它没有找到表articles(或任何表).当我停在种子文件的开头并查看数据库(开发)时,表存在,但测试数据库为空
  • 我已经打印了 Rails.env,它返回了 development.但是,失败消息指出它尝试加载数据库 app_test.articles 而不是 app_development.articles.
  • First of all it doesn't find the table articles (or any table). When I halt at the beginning of my seed file and look into the DB (development), the tables are present, but the test db is empty
  • I've printed the Rails.env and it returns development. However the failure message states that it tries to load the DB app_test.articles and not app_development.articles.

所以我认为这两个问题是相关的.

So I think this two issues are related.

推荐答案

我自己找到了解决方案.问题是,任务 Rake::Task['db:test:prepare'].invoke 将环境更改为 test,因此将该行放在脚本和一切正常:

I found the solution myself. The problem was, that the task Rake::Task['db:test:prepare'].invoke changes the environment to test, so putting that line to the bottom of the script and everything works:

namespace :db do
  task setup_seed: :environment do
    Rake::Task['db:drop'].invoke
    Rake::Task['db:create'].invoke
    Rake::Task['db:schema:load'].invoke
    Rake::Task['db:migrate'].invoke
    Rake::Task['db:seed'].invoke
    Rake::Task['db:test:prepare'].invoke # this one should be at the bottom
  end
end

这篇关于数据库的自定义耙任务:找不到表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆