8

我想在我的 S3 存储桶中有不同的文件夹,以使生产数据库远离开发环境。我不知道该怎么做,这是我在载波初始化程序中提出的骨架:

if Rails.env.test? or Rails.env.development?
   CarrierWave.configure do |config|
     //configure dev storage path
   end
end

if Rails.production?
   CarrierWave.configure do |config|
     //configure prod storage path
   end
end
4

3 回答 3

5

两种选择:

选项1:您不关心按模型 ID 组织文件

在您的carrierwave.rb初始化程序中:

Rails.env.production? ? (primary_folder = "production") : (primary_folder = "test")

CarrierWave.configure do |config|
  # stores in either "production/..." or "test/..." folders
  config.store_dir = "#{primary_folder}/uploads/images"
end

选项 2:您确实关心按模型 ID(即用户 ID)组织文件

在您的上传文件中(即image_uploader.rbuploaders目录中):

class ImageUploader < CarrierWave::Uploader::Base

  ...

  # Override the directory where uploaded files will be stored.
  def store_dir
    Rails.env.production? ? (primary_folder = "production") : (primary_folder = "test")

    # stores in either "production/..." or "test/..." folders
    "#{primary_folder}/uploads/images/#{model.id}"
  end

  ...

end
于 2011-08-04T12:10:38.803 回答
3

考虑以下初始化程序:

#config/initializers/carrierwave.rb

CarrierWave.configure do |config|
  config.enable_processing = true

  # For testing, upload files to local `tmp` folder.
  if Rails.env.test?
    config.storage = :file
    config.root = "#{Rails.root}/tmp/"
  elsif Rails.env.development?
    config.storage = :file
    config.root = "#{Rails.root}/public/"
  else #staging, production
    config.fog_credentials = {
      :provider              => 'AWS',
      :aws_access_key_id     => ENV['S3_KEY'],
      :aws_secret_access_key => ENV['S3_SECRET']
    }
    config.cache_dir = "#{Rails.root}/tmp/uploads" # To let CarrierWave work on heroku
    config.fog_directory    = ENV['S3_BUCKET']
    config.fog_public     = false
    config.storage = :fog
  end
end
  • 在开发中,上传被发送到本地公共目录。
  • 在测试模式下,到 Rails tmp 目录。
  • 最后,在“else”环境(通常是生产或暂存环境)中,我们使用环境变量将文件定向到 S3 以确定要使用的存储桶和 AWS 凭证。
于 2015-05-25T17:19:12.427 回答
0

为您的不同环境使用不同的 Amazon s3 存储桶。在您的各种环境 .rb 文件中,设置环境特定的asset_host. 然后你可以避免在你的上传器中检测到 Rails 环境。

例如,在 production.rb 中:

config.action_controller.asset_host = "production_bucket_name.s3.amazonaws.com"

development.rb 中的asset_host 变为:

config.action_controller.asset_host = "development_bucket_name.s3.amazonaws.com"

等等

(也可以考虑使用 CDN 而不是直接从 S3 托管)。

然后你的上传者变成:

class ImageUploader < CarrierWave::Uploader::Base

  ...

  # Override the directory where uploaded files will be stored.
  def store_dir
    "uploads/images/#{model.id}"
  end

  ...

end

从在您的各种其他环境中复制生产的角度来看,这是一种更好的技术。

于 2013-04-06T21:41:12.650 回答