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

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

Asked on January 10, 2019 in Ruby on Rails.
Add Comment


  • 3 Answer(s)

    Rails create  configuration object: 

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

    The database configuration file (database.yml)  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"]
    ...
    

    Answered on January 10, 2019.
    Add Comment

    Follow this command on  rail database: 

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

    Answered on January 10, 2019.
    Add Comment

    Alternative solution for database, 

    ActiveRecord::Base.connection_config
    

    Configuration in a hash:

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

    Answered on January 10, 2019.
    Add Comment


  • Your Answer

    By posting your answer, you agree to the privacy policy and terms of service.