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

部署Rails+Nginx+Puma应用时生产环境数据库创建失败问题

解决Rails生产环境数据库创建失败的问题

嘿,我一眼就定位到你遇到的问题啦!从错误提示Couldn't create '' database和你的database.yml配置来看,生产环境的数据库名称字段是空的,这就是导致no implicit conversion of nil into String错误的根本原因——Rails完全不知道要创建哪个数据库。

问题分析

你的database.yml里production配置块的database:项没有填写具体的数据库名称,是空值:

production:
  <<: *default
  host: localhost
  adapter: postgresql
  encoding: utf8
  database:  # 这里是空的!没有指定数据库名称
  pool: 5
  username: user
  password: mdp

当你运行RAILS_ENV=production rake db:create时,Rails尝试使用这个空值去执行数据库创建操作,自然会触发类型转换错误。

修复步骤

1. 完善database.yml的生产环境配置

给database字段填上具体的数据库名称,比如你的应用叫my_rails_app,可以设置为my_rails_app_production。修改后的production配置应该是这样的:

production:
  <<: *default
  host: localhost
  adapter: postgresql
  encoding: utf8
  database: my_rails_app_production  # 这里填上你的专属数据库名
  pool: 5
  username: user
  password: mdp

2. 确保PostgreSQL相关依赖已就绪

  • 如果你还没在Ubuntu上安装PostgreSQL,先执行安装命令:
    sudo apt-get update
    sudo apt-get install postgresql postgresql-contrib
    
  • 生产环境用PostgreSQL替代了SQLite,确保Gemfile里添加了对应的gem:
    在Gemfile中添加(如果还没有的话):
    gem 'pg', group: :production
    
    然后执行依赖安装:
    bundle install --without development test
    

3. 验证数据库用户权限

确保你配置的user用户在PostgreSQL中存在,并且拥有创建数据库的权限:

  • 切换到postgres系统用户:
    sudo su - postgres
    
  • 进入PostgreSQL命令行:
    psql
    
  • 创建用户并赋予创建数据库权限(如果用户不存在的话):
    CREATE USER user WITH PASSWORD 'mdp';
    ALTER USER user CREATEDB;
    
  • 退出PostgreSQL和postgres用户:
    \q
    exit
    

4. 重新运行数据库创建命令

现在再执行:

RAILS_ENV=production rake db:create

应该就能成功创建生产环境数据库啦!

内容的提问来源于stack exchange,提问作者Estéban Simal

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.29 11:22:47