如何检查 ActiveRecord 使用的数据库名称

在 datase.yml 中定义所有设置。如何从 Ruby 访问这些设置?我在 App::Application::config里找过了,但是找不到。此外,我记得人们能够配置数据库设置没有 yaml,有人知道如何?

55175 次浏览
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"]

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.

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

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.

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

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]