Rails部署后生产环境中图片无法显示

6
我使用AWS Opswork来部署我的Rails应用程序。我使用Unicorn + Nginx,但是在过去两天里一直被这个错误困扰:虽然我的应用程序能够正常工作,并且进行了rake assets:precompile后css和javascript也能正常工作,但是我无法在应用程序中看到任何图像或fa图标。所有的图像都存储在app/assets/images中,在HTML视图中像这样使用:<img src="/assets/image.jpg">。我的图像在开发环境中能够正常加载,但是在生产环境中却不能。
3个回答

8

我遇到了这个问题。我需要重新编译我的资产。

  1. 运行 rake assets:clobber 命令删除以前预编译的资产。
  2. 执行 rake assets:precompile 命令进行预编译。
  3. 重启您的应用程序/服务器。

希望这可以帮助解决问题。


6

请确保您的production.rb设置包括以下内容:

# Disable Rails's static asset server (Apache or nginx will already do this)
config.serve_static_assets = false

# Don't fallback to assets pipeline if a precompiled asset is missed
config.assets.compile = false

# Generate digests for assets URLs
config.assets.digest = true

这是如何使用SCSS预编译资产的方法:
#application.css.scss (yes, you need to rename it)
@import 'layout/body'


#app/assets/stylesheets/layout/body.css.scss
body {
    background: asset_url('image.jpg')
}

当您执行上述操作时,请确保按照以下方式预编译:
RAILS_ENV=production rake assets:precompile

我刚刚通过ssh登录aws实例,执行了rake assets:precompile命令。 - user4965201
但是我的CSS和JavaScript正常工作,您建议的命令能让我的图像工作吗? - user4965201
@user4965201 是的,它应该可以工作。请确保按照上面建议的预编译资产,并在此之后运行 sudo service unicorn restart - Dusht
@user4965201 我已经编辑了我的回答。如果有帮助,请告诉我! - Dusht
让我们在聊天中继续这个讨论 - user4965201
显示剩余2条评论

0

在 Rails 中以 Rails 的方式编写图像标签,而不是像 HTML 一样:

image_tag("icon.png")
# => <img alt="Icon" src="/assets/icon.png" />
image_tag("icon.png", size: "16x10", alt: "Edit Entry")
# => <img src="/assets/icon.png" width="16" height="10" alt="Edit Entry" />

rake assets:precompile 会将应用程序的资源生成到 public 文件夹中,并从 public/assets 文件夹中获取(预编译的图像、CSS、JS)。


但是我该如何在CSS文件中实现这个呢? - user4965201
不需要更改CSS,Rails预编译CSS文件并从public/assets文件夹映射图像。 - dr. strange

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接