Custom rake task for DB: Table not found

牧云@^-^@ 提交于 2019-12-23 15:43:38

问题


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

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:

  • 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.


回答1:


It looks like you are running your rake task in development environment, but db:test:prepare runs in test by default. Try invoking:

RAILS_ENV=test rake db:setup_seed



回答2:


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


来源:https://stackoverflow.com/questions/36125355/custom-rake-task-for-db-table-not-found

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!