Rails 6 中的 ActionView::Template::Error (资产不存在于资产管道中。)

NZi*_*ool 3 ruby-on-rails

我将图像“jumbotron.jpeg”放置在app/assets/images文件夹中,我在视图中使用该图像:

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

它在开发中运行良好,但当我推送到生产时,我遇到了以下错误:

ActionView::Template::Error (The asset "jumbotron" is not present in the asset pipeline.):
Run Code Online (Sandbox Code Playgroud)

这里还有另一个主题提到同一问题: Rails - 使用 image_tag 时资产不存在于资产管道中

我找到的解决方案是将以下内容设置为 true config/environments/production.rb

  config.assets.compile = true
Run Code Online (Sandbox Code Playgroud)

它确实有效,但它使加载页面变得非常慢。这篇文章还解释了为什么将 config.assets.compile 设置为 true 是一个坏主意: https: //stackoverflow.com/a/8827757/11293450

因此,我尝试做的(设置回来后config.assets.compile = false)是在本地预编译资产(参见https://guides.rubyonrails.org/asset_pipeline.html#local-precompilation)。

我更改config/environments/production.rb为添加这一行:

  config.assets.prefix = "/dev-assets"
Run Code Online (Sandbox Code Playgroud)

然后跑:

rake assets:precompile 
Run Code Online (Sandbox Code Playgroud)

public/ 文件夹中创建了一个dev-assets文件夹文件夹。

在服务器上部署之前,我将文件推送到版本控制:

  1. git push从我的本地环境到Github
  2. git pull在我的生产服务器(VPS)上,然后:
  3. bundle install --deployment --without development test
  4. bundle exec rake assets:precompile db:migrate RAILS_ENV=production
  5. passenger-config restart-app $(pwd)

但我仍然遇到同样的错误:

ActionView::Template::Error (The asset "jumbotron" is not present in the asset pipeline.):
Run Code Online (Sandbox Code Playgroud)

编辑:解决方案如下所述,需要文件的全名。作为旁注,原始文件是 a.jpeg并且我最初编写了<%= image_path 'jumbotron.jpeg' %>它触发了错误。后来我注意到 Rails 实际上将文件扩展名从 更改.jpeg.jpg.

正如这里所指出的:

从 3.0 开始,JPEG 自动转换为 .jpg(均存在实际预编译错误和沙箱预编译错误)。如果您有类似 image_tag('image.jpeg') 的内容,则会出现 AssestNotPrecompiled 错误。将文件重命名为 image.jpg 即可修复该问题。

jam*_*esc 9

<%= image_path 'jumbotron' %> 如果您更改 为会发生什么 <%= image_path 'jumbotron.jpeg' %>

您需要完整的文件名

  • 谢谢,解决了!实际上,原始图像(在编译之前)具有“.jpeg”扩展名。但 Rails 将它们转换为“.jpg”,这可能是最初的问题。 (5认同)
  • 我们也遇到过这个问题,尤其是 .jpeg 扩展名。将 .jpeg 重命名为 .jpg 修复了它,但这是一个多么奇怪的问题! (4认同)