我的系统是macOX Mojave 10.14
MySQL是MySQL:8.0.16
我的database.yml是:

development:
  adapter: mysql2
  encoding: utf8
  database: dev_database
  reconnect: false
  pool: 5
  username: <%= ENV['RAILS_DEV_DB_USSERNAME'] %>
  password: <%= ENV['RAILS_DEV_DB_PASSWORD'] %>
  socket: /tmp/mysql.sock


并且我已经确认该变量是否有效。使用


  命令行:erb config / database.yml


我可以得到:

development:
  adapter: mysql2
  encoding: utf8
  database: dev_database
  reconnect: false
  pool: 5
  username: root
  password: Wle3S#23sv
  socket: /tmp/mysql.sock


但是,当我启动rails s -e developent并浏览到我的页面时,无法连接到数据库。

mysql - Mysql2::Error使用database.yml中的env变量“对用户的访问被拒绝”-LMLPHP

我现在能做什么?

最佳答案

正如作者arpiagar建议rails 3, how use an ENV config vars in a Settings.yml file?检查他的示例(26)


  当您在.yml文件中引入scriptlet标签时,它更多是erb模板。因此,请先将其作为erb模板阅读,然后加载yml


您可以使用dotenvfigaro宝石(受“十二因子应用程序”方法启发)加载环境变量。

例如,如果您使用dotenv gem

By default, load will look for a file called .env in the current working directory. Pass in multiple files and they will be loaded in order. The first value set for a variable will win.

require 'dotenv'
Dotenv.load('file1.env', 'file2.env')
HOSTNAME = ENV['HOSTNAME']


更多信息,请检查以下提到的链接


http://railsapps.github.io/rails-environment-variables.html
https://www.honeybadger.io/blog/ruby-guide-environment-variables/

10-05 20:34
查看更多