在使用雾宝石时,在哪里为不同的env定义s3桶的名称

问题描述 投票:2回答:2

我正在将我的回形针附件上传到s3,因为在我的模型中我使用雾凭证这样...问题是我需要为不同的env设置不同的桶名,通过在模型中定义为每个env指定的桶,所以我可以在哪里定义它?

has_attached_file :news_logo,
  :storage => :fog,
  :fog_credentials => "#{Rails.root}/config/s3.yml",
  :fog_directory => "s3-bucket-name"

config / s3.yml

development:
  provider: AWS
  aws_access_key_id: xyz
  aws_secret_access_key: xyz
  path_style: true
ruby-on-rails amazon-s3 paperclip fog
2个回答
3
投票

您可以使用Rails.env来自定义您的存储桶名称,例如:

has_attached_file :news_logo,
  :storage => :fog,
  :fog_credentials => "#{Rails.root}/config/s3.yml",
  :fog_directory => "s3-bucket-name-#{Rails.env}"

你也可以这样做:

has_attached_file :news_logo,
  :storage => :fog,
  :fog_credentials => "#{Rails.root}/config/s3.yml",
  :fog_directory => (case Rails.env
                       when 'production' then 'my-production-bucket'
                       when 'testing' then 'testing-bucket'
                       else 'this-is-development-bucket';
                     end)

0
投票

修改代码如下

has_attached_file :news_logo,
  :storage => :fog,
  :fog_credentials => "#{Rails.root}/config/s3.yml",
  :fog_directory => S3_BUCKET[Rails.env]

并在常量文件中定义存储桶名称。

配置/初始化/ constants.rb

S3_BUCKET = {
  'development' => 's3-bucket-name-development',
  'staging' => 's3-bucket-name-staging',
  'production' => 's3-bucket-name-production'
}.freeze
© www.soinside.com 2019 - 2024. All rights reserved.