environment change in rake task
Posted
by
Mellon
on Stack Overflow
See other posts from Stack Overflow
or by Mellon
Published on 2011-11-28T09:41:27Z
Indexed on
2011/11/28
9:51 UTC
Read the original article
Hit count: 371
I am developing Rails v2.3 app with MySQL database and mysql2
gem. I faced a weird situation which is about changing the environment in rake task.
(all my setting and configurations for environment and database are correct, no problem for that.)
Here is my simple story :
I have a rake task like following:
namespace :db do
task :do_something => :environment do
#1. run under 'development' environment
my_helper.run_under_development_env
#2. change to 'custom' environment
RAILS_ENV='custom'
Rake::Task['db:create']
Rake::Task['db:migrate']
#3. change back to 'development' environment
RAILS_ENV='development'
#4. But it still run in 'customer' environment, why?
my_helper.run_under_development_env
end
end
The rake task is quite simple, what it does is:
1. Firstly, run a method from my_helper
under "development" environment
2. Then, change to "custom" environment and run db:create
and db:migrate
until now, everything is fine, the environment did change to "custom"
3. Then, change it back again to "development" environment
4. run helper method again under "development" environment
But, though I have changed the environment back to "development" in step 3, the last method still run in "custom" environment, why? and how to get rid of it?
--- P.S. ---
I have also checked a post with the similar situation here, and tried to use the solution there like (in step 2):
ActiveRecord::Base.establish_connection('custom')
Rake::Task['db:create']
Rake::Task['db:migrate']
to change the database connection instead of changing environment but, the db:create
and db:migrate
will still run under "development" database, though the linked post said it should run for "custom" database... weird
© Stack Overflow or respective owner