[英]How to drop test and development database in one rake task?
I tried to drop the test and development databases from one rake task like this: 我试图从一个rake任务中删除测试和开发数据库,如下所示:
task :regenerate do
Rails.env = "test"
Rake::Task["db:drop"].invoke
Rails.env = "development"
Rake::Task["db:drop"].invoke
end
The test database was dropped successfully. 测试数据库已成功删除。 But the development database was not dropped.
但是开发数据库没有被删除。
Any ideas on how to make this work? 关于如何使这项工作的任何想法?
NB: This is on Rails 3.2.3 注意:这是在Rails 3.2.3上
UPDATE: 更新:
Very odd, but reversing the order works: 非常奇怪,但逆转顺序有效:
task :regenerate do
Rails.env = "development"
Rake::Task["db:drop"].invoke
Rails.env = "test"
Rake::Task["db:drop"].invoke
end
What is going on?! 到底是怎么回事?!
You can write it like this: 你可以像这样写:
namespace :db do
desc "Database custom drop"
task :mydrop do
system("rake db:drop RAILS_ENV=test")
system("rake db:drop RAILS_ENV=development")
end
end
Reversing it does work, because there is some strange code in database_tasks.rb
: 反转它确实有效,因为
database_tasks.rb
有一些奇怪的代码:
def each_current_configuration(environment)
environments = [environment]
environments << 'test' if environment == 'development'
configurations = ActiveRecord::Base.configurations.values_at(*environments)
configurations.compact.each do |configuration|
yield configuration unless configuration['database'].blank?
end
end
It always adds test
if env is development
. 如果env是
development
它总是添加test
。 I solved the case of wanting to do a custom db:rebuild
task for simultaneous development
and test
by running development
first, and test
second. 我解决了想要做一个自定义的情况下
db:rebuild
的任务,同时development
和test
运行development
第一,并test
第二。 In addition, before running the tasks, I call my set_env
method which makes sure to set ActiveRecord::Tasks::DatabaseTasks.env
, without this, the database connections don't seem to be handled discretely for environments as expected. 此外,在运行任务之前,我调用我的
set_env
方法,该方法确保设置ActiveRecord::Tasks::DatabaseTasks.env
,如果没有这个,数据库连接似乎不会按预期对环境进行离散处理。 I tried all other sorts of disconnect etc, but this worked without further code. 我尝试了所有其他类型的断开等,但这没有进一步的代码。
def set_env(env)
Rails.env = env.to_s
ENV['RAILS_ENV'] = env.to_s
ActiveRecord::Tasks::DatabaseTasks.env = env.to_s
end
Here is a gist of my full db.rake
file with simultaneous multi-environment db:rebuild
and db:truncate
这是我的完整
db.rake
文件的要点,同时具有多环境db:rebuild
和db:truncate
On my system with Ruby 2 and Rails 3.2.13 I can run rake db:drop 在我使用Ruby 2和Rails 3.2.13的系统上,我可以运行rake db:drop
This drops both test and development databases. 这会丢弃测试和开发数据库。 Much easier now than messing with rake tasks
现在比捣乱rake任务容易得多
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.