I have a Rails 4 application that uses two MySQL databases (primary, secondary). Both databases are configured for development, production and test environments in the database.yml
file:
development:
...
database: primary
...
production:
...
database: primary
...
test:
...
database: primary
...
secondary_development:
...
database: secondary
...
secondary_production:
...
database: secondary
...
secondary_test:
...
database: secondary
...
For now I only have one model that is stored in the secondary db. Below is the migration code that creates a table for this model:
class CreateTags < ActiveRecord::Migration
ActiveRecord::Base.establish_connection "secondary_#{Rails.env}"
def change
create_table :tags do |t|
t.string :name
t.integer :account_id
t.timestamps
end
end
end
When I run rake db:migrate
, the table is correctly created in the secondary database. But when I run rake db:migrate
a second time, it shows me an error table already exists
, which I think related to the fact that rake task adds migration version to versions table of primary database. I am ignoring this for now.
But, when I run some unit test using rake test TEST=test/path_to_test_file.rb
, it shows me an error saying Tags table does not exist
in the secondary DB. I've checked the logs and found that Tags
table is created, BUT in PRIMARY database which is wrong.
So, in short, how to change the migration code to make sure that Tags
table will always be created in the secondary DB?
I have tried:
But it is not working for me :(
UPDATE 1:
Based on @User089247 suggestion, I have tried to run RAILS_ENV=test rake db:create and RAILS_ENV=test rake db:migrate. It says that my primary database is already created which is true, but it says nothing about my secondary databse because secondary DB has separate configuraion secondary_test
. Based on my understanding, it should be possible to create custom rake task (or override existing one) but then this taks should be used by rake test
. Is it possible ? Or am I missing somethings ?