Can you have multiple database.yml files?

Hello! We have an internal gem for replicas, but we are working to migrate off of that to native Rails. Is it possible to have 2 different database.yml files (i.e. database.yml and database_old.yml) and conditionally load one based on an environment toggle? If yes, how/where would you tell Rails to load which YAML file? Thanks so much!

  • Rails version:
  • Ruby version: 3.0.6

Rails 6.1 has support for database switching. You would define multiple database settings in one database.yml tho. See Multiple Databases with Active Record — Ruby on Rails Guides for more info. If that doesn’t work for you, give the makara gem a try GitHub - instacart/makara: A Read-Write Proxy for Connections; Also provides an ActiveRecord adapter.

1 Like

It looks like I can do the following, and it seems to still work even in Rails 6: ruby on rails - Strategies for overriding database.yml? - Stack Overflow

Oh that’s interesting. But isn’t that for the whole application? Something I’ve done is when using a Rails engine, you can have it connect to a different database. So on Rails 6.1 you could define an initializer and do this

# engines/my_engine/config/initializers/database_connection.rb
Rails.application.reloader.to_prepare do
  MyEngine::ApplicationRecord.connects_to database: { writing: :my_engine, reading: :my_engine }

And make sure to define that :my_engine as a section in your database.yml for the parent app.

So I think you have several options here