如何将S3存储桶URL首先更改为存储桶,然后再将URL更改为第二个

时间:2016-03-09 22:39:35

标签: ruby-on-rails ruby amazon-web-services amazon-s3

我正在使用Paperclip和aws-sdk gems创建rails API应用程序。

该应用将URL保存为字符串。保存的网址如下。

http://s3.amazonaws.com/S3_BUCKET_/profiles/avatars/000/000/001/original/avatar.png?1457514823

我无法打开上面的图片。因为从s3中获取它的URL是以下

http://S3_BUCKET_/s3.amazonaws.com//profiles/avatars/000/000/001/original/avatar.png?1457514823

看看水桶是如何成为第一个?但是保存在数据库中的url有第二个桶吗?如何更改保存的URL以使存储桶成为第一个?

config/initializers/paperclip.rb

Paperclip::Attachment.default_options.update(
  default_url: "https://#{Rails.application.secrets.bucket}.s3-ap-southeast-2.amazonaws.com/" \
               "/profiles/avatars/default/missing.jpg")



config/aws.yml

development: &defaults
  access_key_id:     s3_access_key
  secret_access_key: s3 secret key
  s3_region:         ap-southeast-2

test:
  secret_access_key: s3 secret key

staging:
  <<: *defaults
  access_key_id:     s3_access_key
  secret_access_key: <%= ENV["SECRET_KEY_BASE"] %>

production:
  <<: *defaults
  access_key_id:     s3_access_key
  secret_access_key: <%= ENV["SECRET_KEY_BASE"] %>



profile.rb it has the attachment saved

require "base64"
class Profile < ActiveRecord::Base
  belongs_to :user
  validates :user, presence: true

  has_attached_file :avatar, styles: { thumb: "100x100>" }

  validates_attachment_content_type :avatar, content_type: /image/i

  def avatar_url
    avatar && avatar.url
  end

  def avatar_base64=(image_base64)
    file = Paperclip.io_adapters.for(image_base64)
    file.original_filename = file.content_type.sub("image/", "avatar.")
    self.avatar = file
  end

1 个答案:

答案 0 :(得分:1)

您可以在config/initializers/paperclip.rb中添加默认网址,如下所示:

Paperclip::Attachment.default_options[:url] = ':s3_domain_url'

或者您可以直接在您的环境配置中进行配置,即config/environments/production.rb

config.paperclip_defaults = {
    storage: :s3,
    url: ':s3_domain_url',
    ...
}

重要注意:s3_domain_url是字符串,而不是符号。