我最终database.yml
像这样破解了我的文件
<%= ctrys = ['nl','uk']; main = ENV.fetch('DEFAULT_SHARD'){'nl'}; ctrys.delete(main); ctrys.unshift(main);nil %>
development:
<%= ctrys[0] %>:
<<: *default_database
database: <%= ENV.fetch("DATABASE_DATABASE_#{ctrys[0].upcase}") { Rails.application.credentials.dig(:mysql, :"database_#{ctrys[0]}") } %>
<%= ctrys[1] %>:
<<: *default_database
database: <%= ENV.fetch("DATABASE_DATABASE_#{ctrys[1].upcase}") { Rails.application.credentials.dig(:mysql, :"database_#{ctrys[1]}") } %>
我可以这样使用它:
~prompt% DISABLE_SPRING=true DEFAULT_SHARD="uk" rails
Loading development environment (Rails 7.0.1)
hvg-web(dev)> ActiveRecord::Base.connection.pool.db_config.name
=> "uk"
(spring会缓存它,所以禁用spring)
不过,这个 hack 确实给测试运行者带来了挑战:
/usr/src/app# rspec
Running via Spring preloader in process 2504
Running via Spring preloader in process 2510
Rails couldn't infer whether you are using multiple databases from your database.yml and can't generate the tasks for the non-primary databases. If you'd like to use this feature, please simplify your ERB.
感觉很老套,但它确实有效——也许其他人可以想出一个更好的计划?