Displaying host and database names in Rails

With Rails 3 you can use

Rails.configuration.database_configuration[Rails.env]

or

Rails.application.config.database_configuration[Rails.env]

or

ActiveRecord::Base.connection_config

The Rails::configuration.new answer does not work in Rails 3

config   = Rails::Configuration.new
NoMethodError: undefined method `new' for Rails::Configuration:Module
[...]

If you are using MySQL or Postgres then this works

ActiveRecord::Base.connection.current_database

But this only works with drivers that have implemented that method. For example, it will not work for SQLite.


You can create a rails configuration object and obtain the necessary information from it:

config   = Rails::Configuration.new
host     = config.database_configuration[RAILS_ENV]["host"]
database = config.database_configuration[RAILS_ENV]["database"]

See the documentation for Rails::Configuration for details.


On Rails 3, this is most easily accessed via Rails::Application.config, like so:

    YourApplicationClassName::Application.config.database_configuration[::Rails.env]

If you try to call it directly on Rails instead of YourApplicationClassName, rails will give you a deperecation warning. If you don't know what your application constant is, try Rails.application.class.name in a Rails console for your app.


The method below is nice when you are connected to multiple databases. Tested on Sqlite3 and Mysql2

MyModel.connection.instance_variable_get(:@config)[:database]