你能在Rails中获得DB用户名,密码,数据库名称吗?

Eth*_*han 140 ruby database environment activerecord ruby-on-rails

我正在编写一个rake任务,在Rails/ActiveRecord之外执行一些数据库工作.

有没有办法获得当前环境中的数据库连接信息(主机,用户名,密码,数据库名称)database.yml

我想得到它所以我可以用它来连接这样......

con = Mysql.real_connect("host", "user", "pw", "current_db")
Run Code Online (Sandbox Code Playgroud)

Rob*_*ble 234

在rails中,您可以创建配置对象并从中获取必要的信息:

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"]
Run Code Online (Sandbox Code Playgroud)

有关详细信息,请参阅Rails :: Configuration 的文档.

这只是使用YAML :: load从数据库配置文件(database.yml)加载配置,您可以自己使用它来从rails环境外部获取信息:

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

  • 在最近的Rails中,您不需要创建配置,您可以通过`Rails.configuration`获取它 (26认同)
  • 小心使用YAML - 现代版本的Rails也将首先通过ERB过滤文件内容. (3认同)

Ken*_*enB 155

布莱恩在上述评论中的答案值得更多曝光:

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

  • 升级到Heroku上的Rails 4.1,我不得不将此行切换为:ActiveRecord :: Base.configurations [Rails.env] (7认同)

qqb*_*enq 74

ActiveRecord::Base.connection_config
Run Code Online (Sandbox Code Playgroud)

返回哈希中的连接配置:

=> {:adapter=>ADAPTER_NAME, :host=>HOST, :port=>PORT, 
    :database=>DB, :pool=>POOL, :username=>USERNAME, 
    :password=>PASSWORD} 
Run Code Online (Sandbox Code Playgroud)

正如tpett他们的评论中所述:此解决方案考虑将配置database.yml与环境变量合并DATABASE_URL.

  • 这似乎是占`database.yml`配置与`DATABASE_URL`环境变量合并唯一的一个. (10认同)

Ale*_*nae 10

从 Rails 6.1 开始,ActiveRecord::Base.connection_config已弃用。较新的访问器是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">
Run Code Online (Sandbox Code Playgroud)


der*_*sm2 6

我认为这是最简单的解决方案。经过一些测试(至少在 Rails 5.2 中)这将正确解析 DATABASE_URL。

 ActiveRecord::Base.configurations[Rails.env]
Run Code Online (Sandbox Code Playgroud)