m33lky
m33lky

Reputation: 7275

how to check the database name that ActiveRecord uses

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?

Upvotes: 103

Views: 76774

Answers (6)

williamlopes
williamlopes

Reputation: 446

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]

Upvotes: 18

Weston Ganger
Weston Ganger

Reputation: 6712

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")"

Upvotes: 3

fairchild
fairchild

Reputation: 130

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.

Upvotes: 11

iGEL
iGEL

Reputation: 17392

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

Upvotes: 103

tommyb67
tommyb67

Reputation: 21

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.

Upvotes: 2

tsherif
tsherif

Reputation: 11710

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"]

Upvotes: 151

Related Questions