在 rails 的 ENV 变量中存储密码时收到 "PG::ConnectionBad fe_sendauth: no password supplied" 错误

receiving "PG::ConnectionBad fe_sendauth: no password supplied" error when storing passwords in ENV variables in rails

我最近将数据库从 sqlite3 切换到了 PG。我的 pg 用户名和密码是硬编码的,虽然它可以工作,但这不是安全的做法。所以我将我的密码存储在 .yml 文件的 ENV 变量中,并在我的 database.yml 文件中引用该变量,但是当我 运行 服务器时,它给我错误“PG::ConnectionBad fe_sendauth:未提供密码

以下是我的pg_keys.yml文件

PG_PASSWORD: "***********" 

下面是我的 database.yml 文件:

default: &default
  adapter: postgresql 
  encoding: unicode 
  pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>
  timeout: 5000

development:
  <<: *default
  database: stockapp_development 
  username: postgres
  password: <%= ENV['PG_PASSWORD'] %>
  host: localhost

# Warning: The database defined as "test" will be erased and
# re-generated from your development database when you run "rake".
# Do not set this db to the same as development or production.
test:
  <<: *default
  database: stockapp_test 
  host: localhost 
  username: postgres
  password: <%= ENV['PG_PASSWORD'] %>

production:
  <<: *default
  database: stockapp_production 
  username: stockapp 
  password: <%= ENV['STOCKAPP_DATABASE_PASSWORD'] %> 

为什么提示没有提供密码?我的 database.yml 没有在其他文件中看到密码吗?我需要导出密码吗?

因为ENV个变量来自https://github.com/bkeepers/dotenv.

通过将此 gem 添加到您的 Gemfile 来安装它,然后 运行 bundle 并在 .env 中设置变量 PG_PASSWORD=***********你的根。那么它应该可以正常工作。