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

Rails数据库初始化命令未按预期创建数据库求助

Rails db:setup 连接PostgreSQL失败的解决办法

问题重现

通过rails new freelancer --database=postgresql --javascript=webpack创建Rails项目后,执行rails db:setup时出现如下报错:

Is the server running locally and accepting connections on that socket? Couldn't create 'freelancer_development' database. Please check your configuration. rails aborted! ActiveRecord::ConnectionNotEstablished: connection to server on socket "/tmp/.s.PGSQL.5432" failed: No such file or directory Is the server running locally and accepting connections on that socket? Caused by: PG::ConnectionBad: connection to server on socket "/tmp/.s.PGSQL.5432" failed: No such file or directory Is the server running locally and accepting connections on that socket? Tasks: TOP => db:setup => db:create (See full trace by running task with --trace)

解决步骤

  • 启动PostgreSQL服务
    报错核心原因是本地PostgreSQL服务未运行,根据操作系统执行对应命令:

    • macOS(Homebrew安装):brew services start postgresql
    • Ubuntu/Debian:sudo systemctl start postgresql
    • Windows:找到PostgreSQL服务手动启动,或执行pg_ctl start -D "你的PostgreSQL数据存储目录"
  • 修正socket路径匹配问题
    若服务已启动仍报错,大概率是database.yml中的socket路径与PostgreSQL实际路径不匹配:

    1. 进入PostgreSQL命令行:psql -U postgres
    2. 查询实际socket目录:show unix_socket_directories;
    3. 打开config/database.yml(注意路径是config/database.yml而非你提到的config/locales/database.yml),修改对应环境的socket配置项,示例:
      development:
        adapter: postgresql
        encoding: unicode
        database: freelancer_development
        pool: 5
        socket: /var/run/postgresql/.s.PGSQL.5432 # 替换为查询到的路径
      test:
        adapter: postgresql
        encoding: unicode
        database: freelancer_test
        pool: 5
        socket: /var/run/postgresql/.s.PGSQL.5432
      
  • 验证并重新执行命令
    先通过psql -U postgres测试能否正常连接PostgreSQL,确认无误后再次执行rails db:setup,即可自动创建freelancer_development和freelancer_test数据库。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.02 13:05:19