Support for dynamic database switch


currently in my project I’ve implemented support in AR to create different connection pools and switch between them depending on user’s input.

Currently rails give you an option to override connection per model, but there is no way to change this connection dynamically based on user locale, or subdomain, or anything else.

Also there is no easy way to change connection for a whole app (especially when using threaded servers like puma)

I’m curios is there any need for such functionality or this is only my edge case? Quick search shows that there was some interest in this

My draft API proposition is:

Add any number of DB’s to config/database.yml with underscores:




and just in your app code set currently needed connection

ActiveRecord::Base.current_active_connection = :alternative

Behind the scenes AR will create separate connection pool for an each namespace and will use specified.

What do you think? I will create a PR if anyone need this besides me

I think what you want can be done using something like now, but we are planning to work on multi databases for the next Rails version, Jeremy Kemper is assigned for this task.