Can you get DB username, pw, database name in Rails?

Ruby on-RailsRubyDatabaseActiverecordEnvironment

Ruby on-Rails Problem Overview


I'm writing a rake task that does some DB work outside of Rails/ActiveRecord.

Is there a way to get the DB connection info (host, username, password, DB name) for the current environment as defined in database.yml?

I'd like to get it so I can use it to connect like this...

con = Mysql.real_connect("host", "user", "pw", "current_db")

Ruby on-Rails Solutions


Solution 1 - Ruby on-Rails

From within rails you can create a configuration object and obtain the necessary information from it:

config   = Rails.configuration.database_configuration
host     = config[Rails.env]["host"]
database = config[Rails.env]["database"]
username = config[Rails.env]["username"]
password = config[Rails.env]["password"]

See the documentation for Rails::Configuration for details.

This just uses YAML::load to load the configuration from the database configuration file (database.yml) which you can use yourself to get the information from outside the rails environment:

require 'YAML'
info = YAML::load(IO.read("database.yml"))
print info["production"]["host"]
print info["production"]["database"]
...

Solution 2 - Ruby on-Rails

Bryan's answer in the comment above deserves a little more exposure:

>> Rails.configuration.database_configuration[Rails.env]
=> {"encoding"=>"unicode", "username"=>"postgres", "adapter"=>"postgresql", "port"=>5432, "host"=>"localhost", "password"=>"postgres", "database"=>"mydb", "pool"=>5}

Solution 3 - Ruby on-Rails

ActiveRecord::Base.connection_config

returns the connection configuration in a hash:

=> {:adapter=>ADAPTER_NAME, :host=>HOST, :port=>PORT, 
    :database=>DB, :pool=>POOL, :username=>USERNAME, 
    :password=>PASSWORD} 

As tpett remarked in their comment: this solution accounts for merging the configuration from database.yml and from the environment variable DATABASE_URL.

Solution 4 - Ruby on-Rails

I think this is the simplest solution. After some testing (in Rails 5.2 at least) this will resolve DATABASE_URL correctly.

 ActiveRecord::Base.configurations[Rails.env]

Solution 5 - Ruby on-Rails

As of Rails 6.1, ActiveRecord::Base.connection_config is deprecated. The newer accessor is ActiveRecord::Base.connection_db_config

[1] pry(main)> ActiveRecord::Base.connection_db_config
=> #<ActiveRecord::DatabaseConfigurations::HashConfig:0x00007fe04ae72e58
 @configuration_hash=
  {:adapter=>"postgresql",
   :encoding=>"utf8",
   :min_messages=>"WARNING",
   :host=>"localhost",
   :username=>"postgres",
   :password=>"P@ssw0rd",
   :port=>5432,
   :database=>"myapp_development"},
 @env_name="development",
 @name="primary">

Solution 6 - Ruby on-Rails

Old question but this was one of my first stops in looking up how to do this so I figure this may help someone else. I normally have .my.cnf files in the home directory. So using the 'parseconfig' gem and some ERB syntax in my database.yml config file means I've got dynamic file that I can feel good about checking into source control and also simplify deployments (in my case). Also note the list of common sockets, this makes it easier to move my app to different operating systems that might have a different Unix socket path.

<% 
	require 'parseconfig'
	c=ParseConfig.new('../../.my.cnf') %>

mysqlevn: &mysql
  adapter: mysql 
  username: <%= c.params['client']['user'] %>
  password: <%= c.params['client']['password'] %>
  host: localhost 
  socket: <%= [ 
  '/var/run/mysqld/mysqld.sock',
  '/var/lib/mysql/mysql.sock',
  '/tmp/mysqld.sock',
  '/tmp/mysql.sock'].detect { |socket| File.exist?(socket) } %>

production:
  database: app_production
  <<: *mysql

  
development:
  database: app_development 
  <<: *mysql
  
# Do not set this db to the same as development or production.
test:
  database: app_test
  <<: *mysql

ref: http://effectif.com/articles/database-yml-should-be-checked-in

Solution 7 - Ruby on-Rails

In Rails 6.1+, you can use:

ActiveRecord::Base.connection_db_config.configuration_hash

This returns a hash containing the current environment's connection information:

{
  :adapter=>"postgresql",
  :encoding=>"utf8",
  :min_messages=>"WARNING",
  :host=>"localhost",
  :username=>"postgres",
  :password=>"P@ssw0rd",
  :port=>5432,
  :database=>"my_app_development"
}

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
QuestionEthanView Question on Stackoverflow
Solution 1 - Ruby on-RailsRobert GambleView Answer on Stackoverflow
Solution 2 - Ruby on-RailsKenBView Answer on Stackoverflow
Solution 3 - Ruby on-RailsqqbenqView Answer on Stackoverflow
Solution 4 - Ruby on-Railsderosm2View Answer on Stackoverflow
Solution 5 - Ruby on-RailsAlex DunaeView Answer on Stackoverflow
Solution 6 - Ruby on-RailsedwardsharpView Answer on Stackoverflow
Solution 7 - Ruby on-RailsdanielricecodesView Answer on Stackoverflow