简体   繁体   中英

Rails 4, Paperclip, Amazon S3 - Upload to a specific folder

This is the first time I'm using Paperclip and Amazon S3 and I'm pretty sure I'm missing something obvious. It would be great if somebody can point it out.

In S3 bucket, I have 2 folders, development and production , to upload images to corresponding folders based on the environment. I tried the solution proposed here as follows in my model.rb -

options = {}

if Rails.env.production?
   options[:path] ||= 'production'
else
   options[:path] ||= 'development'
end

has_attached_file :picture, options

I kept getting a file named development / production uploaded to the S3 bucket (as shown in the screenshot).

在此输入图像描述

I even tried passing the :path as config setting for paperclip. Same thing happened - a folder named development / production was getting uploaded

Am I missing something here? All I want to do, upload pictures I get in the development environment into the development folder and vice versa for production.

The path option needs to specify the file pattern as well. Try this

Model

has_attached_file :picture,
  :storage => :s3,
  :bucket => 'your_bucket',
  :path => ":env_folder/:attachment/:id/:style/:filename.:extension"

# some other model code here ...

private

# interpolate in paperclip
Paperclip.interpolates :env_folder  do |attachment, style|
  Rails.env.production? ? 'production' : 'development'
end

EDIT

If you just leave the :path option as 'development' or 'production' you're telling Paperclip the path to the file is yourbucket/development which is why you're seeing the single file as per your screenshot. This is why it's important to have something that will uniquely identify the resource in the :path option (I used :id in my example which will use the model's id attribute).

If you have the option, I think a better approach would be to separate the environments into their own buckets. In other words, the development environment would have its own bucket and production would have its own separate bucket. Not only is this cleaner within the code, you'll also be able to set different policies per bucket/environment which in my experience is required once your app is released in production. Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM