【问题标题】:Rails assets: How can you reference images from another app?Rails 资产:如何引用其他应用程序中的图像?
【发布时间】:2012-04-18 00:19:48
【问题描述】:

Rails 在预编译期间将图像名称移动到 /public/assets 目录时会为图像名称添加 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 副本没有生成没有指纹的版本吗?

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 nginx assets


    【解决方案1】:

    Rails 使用 image_tag 为您处理:

    image_tag "myimage.jpg"
    

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

    Class AssetsService < ApplicationController  
      def index
      end
    end
    

    index.js.haml

    = image_tag "myimage.jpg"
    

    【讨论】:

      【解决方案2】:

      答案不在于 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;
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-05-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-09-15
        相关资源
        最近更新 更多