我有一个Rails 4应用程序,它使用两个MySQL数据库(主数据库和辅助数据库)。这两个数据库都是为database.yml
文件中的开发、生产和测试环境配置的:
development:
...
database: primary
...
production:
...
database: primary
...
test:
...
database: primary
...
secondary_development:
...
database: secondary
...
secondary_production:
...
database: secondary
...
secondary_test:
...
database: secondary
...
目前,我只有一个存储在辅助数据库中的模型。以下是为该模型创建表的迁移代码:
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
运行rake db:migrate
时,会在辅助数据库中正确创建表。但当我第二次运行rake db:migrate
时,它显示了一个错误table already exists
,我认为这与rake任务将迁移版本添加到主数据库的版本表有关。我现在忽略了这一点。
但是,当我使用rake test TEST=test/path_to_test_file.rb
运行一些单元测试时,它会在辅助数据库中显示一个错误,即Tags table does not exist
。我检查了日志,发现Tags
表已经创建,但在PRIMARY数据库中,这是错误的。
那么,简而言之,如何更改迁移代码以确保Tags
表始终在辅助数据库中创建?
我试过:
- https://stackoverflow.com/a/11020572
- https://stackoverflow.com/a/9652660
但它对我不起作用:(
更新1:根据@User089247的建议,我尝试运行RAILS_ENV=test rake db:create和RAILS_ENV=test rake db:migrate。它说我的主数据库已经创建,这是真的,但它没有说我的辅助数据库,因为辅助数据库有单独的配置secondary_test
。根据我的理解,应该可以创建自定义rake任务(或覆盖现有任务),但rake test
应该使用这个taks。有可能吗?还是我错过了什么?
这里要做的是指定模型上辅助数据库的使用,而不仅仅是在迁移中:
class Tag < ActiveRecord::Base
establish_connection "secondary_#{Rails.env}"
end
如果您要使用多个型号的辅助数据库,此博客文章将提供一些有用的附加信息:http://pragdave.me/blog/2006/01/03/sharing-external-activerecord-connections/