Confirm current database connection in Rails console

Prem Sichanugrist
Sikachu's Blog
Published in
Feb 4, 2022

--

If you are using Rails muti-database feature, it's quite useful to know if you are connecting to the main writer database or a read replica before performing a database query in the Rails console.

The easiest way to do this is to call ActiveRecord::Base.connection_db_config from the console:

> ActiveRecord::Base.connection_db_config
=>
#<ActiveRecord::DatabaseConfigurations::UrlConfig:0x123456
@configuration_hash={...},
@env_name="production",
@name="main",
@url="...">

You can see right away that we’re connecting to the main writer database.

If you want to switch your current database for the remaining of your session, you can use ActiveRecord::Base.connecting_to:

> ActiveRecord::Base.connecting_to(role: :reading)
=> [{:role=>:reading, :shard=>:default, :prevent_writes=>true, :klasses=>[ActiveRecord::Base]}]
> ActiveRecord::Base.connection_db_config.name
=> "reader"

--

--

Senior Developer at Degica. I also contribute to open source projects, mostly in Ruby.