2

在预编译期间将图像名称移动到 /public/assets 目录时,Rails 会为图像名称添加 md5 哈希。问题是这些哈希是不可预测的,所以我怎么知道在尝试链接到它们时会调用什么?

例如,如果我托管一个名为 flowers.jpg 的图像,然后尝试在 www.mysite.com/flowers.jpg 访问它,它会失败,因为该文件已重命名为 flowers-4182172ae014ec23dc02739229c08dcc。

我知道 Rails 有可以自动找到这些图像的助手。但是,如果您尝试从完全不同的网站或应用程序链接到这些图像怎么办?有没有办法让 Rails 说:“我找不到flowers.jpg 的预编译版本,所以我不会从 /public/assets 提供服务,而是从 /app/assets 提供服务。”?

编辑:根据这篇文章(http://stackoverflow.com/questions/10045892/rails-compiles-assets-both-with-and-without-md5-hash-why),Rails 应该同时编译我的资产版本有和没有 md5 哈希?知道为什么我的 Rails 副本没有生成没有指纹的版本吗?

4

2 回答 2

0

Rails 使用 image_tag 为您处理:

image_tag "myimage.jpg"

这将为您提供正确的网址。您也许可以编写一个小服务,为您的 as(未经测试)生成图像 url:

Class AssetsService < ApplicationController  
  def index
  end
end

index.js.haml

= image_tag "myimage.jpg"
于 2012-04-18T00:30:35.763 回答
0

答案不在于 Rails。我认为 Rails 不应该编译没有指纹的图像。但是,它应该仍然能够为它们服务,并且我在我的 nginx 配置文件中添加了一些代码,以防止这种情况发生。这是有问题的代码:

location ~* ^/assets/ {
    # Per RFC2616 - 1 year maximum expiry
    # http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html
    expires 1y;
    add_header Cache-Control public;

    # Some browsers still send conditional-GET requests if there's a
    # Last-Modified header or an ETag header even if they haven't
    # reached the expiry date sent in the Expires header.
    add_header Last-Modified "";
    add_header ETag "";
    break;
}
于 2012-04-18T01:24:52.287 回答