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

Rails 6生产环境遇ActionView模板错误:资产不在资产管道中

解决Rails生产环境中JPEG资产找不到的问题

问题背景

我把图片jumbotron.jpeg放到了app/assets/images目录下,在视图里用这段代码调用:

<div class="jumbotron" style="background: url(<%= image_path 'jumbotron' %>); no-repeat center center fixed;">

开发环境完全正常,但部署到生产环境后就抛出错误:

ActionView::Template::Error (The asset "jumbotron" is not present in the asset pipeline.)

尝试过的无效方案

一开始我在config/environments/production.rb里设置了config.assets.compile = true,虽然能解决报错,但页面加载速度变得极慢,而且这个配置并不是生产环境的最佳实践。

之后我把这个配置改回false,按照官方文档尝试本地预编译资产:

  • 在config/environments/production.rb中添加config.assets.prefix = "/dev-assets"
  • 执行rake assets:precompile,成功在public目录生成了dev-assets文件夹
  • 推送代码到版本控制后部署到VPS生产服务器,执行了这些命令:
    git push 本地代码到Github
    # 生产服务器端操作
    git pull
    bundle install --deployment --without development test
    bundle exec rake assets:precompile db:migrate RAILS_ENV=production
    passenger-config restart-app $(pwd)
    

但还是遇到了同样的资产找不到错误。

最终有效解决方案

问题的根源在于Rails对JPEG文件的扩展名处理!从Rails 3.0开始,框架会自动将.jpeg扩展名转换为.jpg格式。如果你的原始文件是.jpeg,不管你用image_path('jumbotron')还是image_path('jumbotron.jpeg'),预编译后的资产都会是.jpg格式,这就导致了找不到对应资产的错误。

解决方法非常直接:

  1. 将app/assets/images里的jumbotron.jpeg重命名为jumbotron.jpg
  2. 视图里的代码保持<%= image_path 'jumbotron' %>(或者显式写jumbotron.jpg)即可

这样部署到生产环境后,资产就能被正确识别和加载了。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.08 15:28:11