Rails image_tag不使用CDN资产

时间:2017-01-22 17:41:30

标签: ruby-on-rails ruby-on-rails-4 amazon-s3 cdn

我最近为我的应用程序设置了一个CDN,几乎一切正常,比如我的静态资产,我的JS和CSS。

但是一些对象资产(图像)继续使用我的S3 URL来获取数据,例如:

<%= image_tag(@listing.cover.url(:large))%>

在生产中成为:

<img src="https://musicjungle.s3.amazonaws.com/listing_covers/5045/large.jpg?1484594254" class="fotorama__img" style="width: 548px; height: 548px; left: 91px; top: 0px;">

而不是使用我的CDN。为了记录,这是我设置CDN的production.rb的一部分:

#CDN settings
config.action_controller.asset_host = "d1bfllp5zjnl7u.cloudfront.net"

正如我所描述的那样,我的所有其他资产都没有问题,但仍然使用S3。也许这与我的附件助手有关?我创建了一个将应用程序的图像上传到S3,这是代码:

module Shared
  module AttachmentHelper

    def self.included(base)
      base.extend ClassMethods
    end

    module ClassMethods
      def has_attachment(name, options = {})

        # generates a string containing the singular model name and the pluralized attachment name.
        # Examples: "user_avatars" or "asset_uploads" or "message_previews"
        attachment_owner    = self.table_name.singularize
        attachment_folder   = "#{attachment_owner}_#{name.to_s.pluralize}"

        # we want to create a path for the upload that looks like:
        # message_previews/00/11/22/001122deadbeef/thumbnail.png
        attachment_path     = "#{attachment_folder}/:id/:style.:extension"

        if Rails.env.production?
          options[:path]            ||= attachment_path
          options[:storage]         ||= :s3
          options[:s3_credentials]  ||= {
            :bucket => 'bucket-name',
            :access_key_id => 'KEY_ID',
            :secret_access_key => 'ACCESS_KEY'
          }
          options[:s3_permissions]  ||= 'private'
          options[:s3_protocol]     ||= 'https'
          options[:s3_headers]      ||= { 
            'Cache-Control' => 'max-age=315576000', 
            'Expires' => 10.years.from_now.httpdate 
          } 
        else
          # For local Dev/Test envs, use the default filesystem, but separate the environments
          # into different folders, so you can delete test files without breaking dev files.
          options[:path]  ||= ":rails_root/public/system/attachments/#{Rails.env}/#{attachment_path}"
          options[:url]   ||= "/system/attachments/#{Rails.env}/#{attachment_path}"
        end

        # pass things off to paperclip.
        has_attached_file name, options
      end
    end
  end
end

1 个答案:

答案 0 :(得分:0)

尝试在回形针选项中设置s3_host_alias选项:

options[:s3_host_alias] = "d1bfllp5zjnl7u.cloudfront.net"