how to check the database name that ActiveRecord uses

Ruby on-RailsRubyConfiguration

Ruby on-Rails Problem Overview


In database.yml you define all the settings. How can I access those settings from ruby? I've looked in App::Application::config, but can't find it there. Also, I remember people were able to configure database settings without yaml, does anyone know how?

Ruby on-Rails Solutions


Solution 1 - Ruby on-Rails

Rails.configuration.database_configuration

This will give you a hash table with the configurations for each of your environments. E.g. to get your development database name:

Rails.configuration.database_configuration["development"]["database"]

Solution 2 - Ruby on-Rails

In Rails 4.2, you can do this:

ActiveRecord::Base.connection.current_database

You can also ask specific models for their database (since it's possible to use different databases per model):

User.connection.current_database

Solution 3 - Ruby on-Rails

An additional way to get more iformation is to use the database specific connection info methods. For example, if you are using postgresql, you can get details for the current database connection with:

ActiveRecord::Base.connection.raw_connection.conninfo_hash

This will give more connection details, not only those that differ from defaults.

Solution 4 - Ruby on-Rails

Since Rails 6.1 you must use ActiveRecord::Base.connection_db_config. So you can access the others class methods, like database().

db_config = ActiveRecord::Base.connection_db_config
print db_config.database
# main available methods: [:host, :schema_cache_path, :migrations_paths, :config, :database, :_database=, :checkout_timeout, :reaping_frequency, :idle_timeout, :replica?, :configuration_hash, :adapter, :pool]

Solution 5 - Ruby on-Rails

To piggyback on the comments from tsherif, you can run the Rails.configuration commands inside the rails console (rails c) to get the database names.

Solution 6 - Ruby on-Rails

If you want to get the database name for use within a bash or shell script then use the following:

db_name="$(bundle exec rails runner "puts ActiveRecord::Base.connection.current_database")"

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionm33lkyView Question on Stackoverflow
Solution 1 - Ruby on-RailstsherifView Answer on Stackoverflow
Solution 2 - Ruby on-RailsiGELView Answer on Stackoverflow
Solution 3 - Ruby on-RailsfairchildView Answer on Stackoverflow
Solution 4 - Ruby on-RailswilliamlopesView Answer on Stackoverflow
Solution 5 - Ruby on-Railstommyb67View Answer on Stackoverflow
Solution 6 - Ruby on-RailsWeston GangerView Answer on Stackoverflow