You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

执行rails db:setup时PostgreSQL无密码认证失败问题求助

解决Rails执行rails db:setup时的PostgreSQL连接认证错误

问题描述

执行rails db:setup命令时触发ActiveRecord::ConnectionNotEstablished错误,具体提示:

connection to server at "localhost" (::1), port 5432 failed: fe_sendauth: no password supplied
Couldn't create 'reservify_back_end_development' database. Please check your configuration.
rails aborted!
ActiveRecord::ConnectionNotEstablished: connection to server at "localhost" (::1), port 5432 failed: fe_sendauth: no password supplied 

当前config/database.yml的核心配置片段:

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

development:
  <<: *default
  database: reservify_back_end_development
  #username: reservify_back_end
  #password:
  #host: localhost
  #port: 5432

解决办法

方法1:在database.yml中配置PostgreSQL认证信息

打开config/database.yml,取消development段中username和password的注释,填写你的PostgreSQL用户(通常默认是postgres)的用户名和密码:

development:
  <<: *default
  database: reservify_back_end_development
  username: postgres # 替换为你的PostgreSQL用户名
  password: your_postgres_password # 替换为你的PostgreSQL密码

保存文件后,重新执行rails db:setup。

方法2:修改PostgreSQL配置信任本地连接(仅开发环境推荐)

  1. 找到PostgreSQL的pg_hba.conf配置文件:
    • macOS(Homebrew安装):/usr/local/var/postgres/pg_hba.conf 或 /opt/homebrew/var/postgres/pg_hba.conf
    • Linux:/etc/postgresql/[你的PostgreSQL版本]/main/pg_hba.conf
    • Windows:C:\Program Files\PostgreSQL\[你的PostgreSQL版本]\data\pg_hba.conf
  2. 找到IPv4和IPv6本地连接的配置行,将认证方式从scram-sha-256或md5改为trust:
    # 修改前
    host    all             all             127.0.0.1/32            scram-sha-256
    host    all             all             ::1/128                 scram-sha-256
    
    # 修改后
    host    all             all             127.0.0.1/32            trust
    host    all             all             ::1/128                 trust
    
  3. 重启PostgreSQL服务:
    • macOS:brew services restart postgresql
    • Linux:sudo systemctl restart postgresql
    • Windows:打开服务管理器,找到PostgreSQL服务并重启
  4. 重新执行rails db:setup。

方法3:使用环境变量传递数据库认证信息(更安全)

通过环境变量DATABASE_URL传递完整的数据库连接信息,避免在配置文件中明文存储密码:

  • 终端临时设置:
    export DATABASE_URL="postgres://postgres:your_password@localhost/reservify_back_end_development"
    
  • 若要永久生效,可将上述命令添加到你的shell配置文件(如.bashrc、.zshrc)中。
    设置完成后执行rails db:setup即可。

内容的提问来源于stack exchange,提问作者Hamza

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.22 15:50:46