jadent
jadent

Reputation: 3904

How to run db:migrate from another rake task with parameters?

I'd like to call db:drop, db:create, db:migrate from another rake task and specify the database like the command "rake db:migrate db=test". That way I can call it for several different databases in a row.

But settings Rails.env = 'test' and then resetting it Rails.env to a new environment doesn't work.

But the above code always executes on the development environment (if i take out the development environment I'll get this error

How can I call these tasks multiple times and change the environment to us?

Upvotes: 1

Views: 1450

Answers (2)

jadent
jadent

Reputation: 3904

Once ActiveRecord sets the environment you have to tell it directly to change the environment. So this will work.

ActiveRecord::Tasks::DatabaseTasks.env = 'test'
Rake::Task["db:drop"].execute
Rake::Task["db:create"].execute
Rake::Task["db:migrate"].execute 

ActiveRecord::Tasks::DatabaseTasks.env = 'development'
Rake::Task["db:drop"].execute
Rake::Task["db:create"].execute
Rake::Task["db:migrate"].execute   

Upvotes: 2

infused
infused

Reputation: 24367

If you only want to use the test database temporarily, set the database connection to test and then set it back to the defaults when the task is finished:

Rails.env = 'test
Rake::Task['db:migrate'].invoke
Rails.env = ENV["RAILS_ENV"]

Upvotes: 0

Related Questions