Heroku上的Rails 4有一个奇怪的问题。当图像被编译时,它们被添加了散列,但从CSS中引用这些文件时没有适当的名称调整。这就是我的意思。我有一个叫logo。png的文件。然而,当它出现在heroku上时,它被视为:

/assets/logo-200a00a193ed5e297bb09ddd96afb953.png

然而,CSS仍然声明:

background-image:url("./logo.png");

结果是:图像无法显示。有人遇到过这种情况吗?如何解决这个问题?


当前回答

散列是因为资产管道和服务器优化缓存 http://guides.rubyonrails.org/asset_pipeline.html

试试这样做:

 background-image: url(image_path('check.png'));

古德勒克

其他回答

我摆弄了几个小时后发现:

工作原理:

background-image: url(image_path('transparent_2x2.png')); 

// how to add attributes like repeat, center, fixed?

上面的输出类似于:“/assets/transparent_2x2-ec47061dbe4fb88d51ae1e7f41a146db.png”

注意前面的“/”,它在引号内。 还要注意stylesheet.css.scss中的scss扩展和image_path帮助器。图片在app/assets/images目录下。

不工作:

background: url(image_path('transparent_2x2.png') repeat center center fixed;

无效属性:

background:url(/assets/pretty_photo/default/sprite.png) 2px 1px repeat center fixed;

我最后的办法是把这些放到我的公共s3桶里,然后从那里加载,但最后还是有了一些东西。

不知道为什么,但唯一对我有用的是使用asset_path而不是image_path,即使我的图像是在assets/images/目录下:

例子:

app/assets/images/mypic.png

在Ruby中:

asset_path('mypic.png')

在.scss:

url(asset-path('mypic.png'))

更新:

弄清楚了-原来这些资产助手来自sass-rails gem(我已经安装在我的项目中)。

默认情况下,Rails 4不会为您的资产服务。要启用此功能,您需要进入配置/应用程序。Rb,加上这一行:

config.serve_static_assets = true

https://devcenter.heroku.com/articles/rails-4-asset-pipeline#serve-assets

在Rails 4中,你可以像这样在你的.SCSS文件中引用位于assets/images/中的图像:

.some-div {
  background-image: url(image-path('pretty-background-image.jpg'));
}

当你以开发模式启动应用程序时(localhost:3000),你应该会看到如下内容:

background-image: url("/assets/pretty-background-image.jpg");

在生产模式下,你的资产将有缓存助手编号:

background-image: url("/assets/pretty-background-image-8b313354987c309e3cd76eabdb376c1e.jpg");

只有这个片段不适合我:

background-image: url(image_path('transparent_2x2.png'));

但是要重命名stylename。SCSS到stylename.css.scss帮助我。