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

Windows11下Rails迁移数据库遇ActiveRecord连接错误求助

问题描述

系统环境:Windows 11
依赖版本:

ruby "2.7.3"
# 可选捆绑开发版Rails:gem "rails", github: "rails/rails", branch: "main"
gem "rails", "~> 7.0.7"
# 使用PostgreSQL作为Active Record数据库
gem "pg", "~> 1.1"

首次执行rails db:migrate时触发如下错误:

rails aborted!
ActiveRecord::ConnectionNotEstablished: connection to server at "localhost" (::1), port 5432 failed: Connection refused (0x0000274D/10061)
Is the server running on that host and accepting TCP/IP connections?
connection to server at "localhost" (127.0.0.1), port 5432 failed: Connection refused (0x0000274D/10061)
Is the server running on that host and accepting TCP/IP connections?

Caused by:
PG::ConnectionBad: connection to server at "localhost" (::1), port 5432 failed: Connection refused (0x0000274D/10061)
Is the server running on that host and accepting TCP/IP connections?
connection to server at "localhost" (127.0.0.1), port 5432 failed: Connection refused (0x0000274D/10061)
Is the server running on that host and accepting TCP/IP connections?

Tasks: TOP => db:migrate
(See full trace by running task with --trace)

已尝试操作:

  • 重装pg gem
  • 尝试在系统服务中查找PostgreSQL服务以重启,未找到
  • 修改数据库连接端口

以上操作均未解决问题,寻求帮助


解决步骤

1. 确认PostgreSQL本体是否安装

pg gem仅为Ruby与PostgreSQL的交互驱动,并非数据库本身。服务中找不到PostgreSQL,大概率是未安装数据库本体:

  • 下载对应Windows版本的PostgreSQL安装包(建议选13+版本,与pg gem兼容性更好)
  • 安装时务必勾选「Register as a Windows service」选项,确保服务自动注册并启动

2. 验证并启动PostgreSQL服务

安装完成后:

  • 按下Win+R输入services.msc打开服务管理器
  • 找到名称为postgresql-x64-xx(xx为版本号,如15)的服务,确认状态为「正在运行」
  • 若未运行,右键选择「启动」

3. 匹配Rails数据库连接配置

修改config/database.yml,确保参数与PostgreSQL实际设置一致:

default: &default
  adapter: postgresql
  encoding: unicode
  pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>
  host: localhost
  port: 5432
  username: postgres # 默认超级用户为postgres
  password: [你安装PostgreSQL时设置的密码]

development:
  <<: *default
  database: [你的项目名]_development

4. 初始化数据库

先执行rails db:create创建开发环境数据库,再执行rails db:migrate

5. 检查防火墙设置

Windows防火墙可能拦截5432端口:

  • 打开Windows Defender防火墙「高级设置」
  • 添加入站规则,允许TCP端口5432的连接

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 10:06:12