At signup of a new user, I would like my Rails application to automatically copy a standard file for that user to my S3 bucket.
How can I use the aws-s3 gem/aws-sdk gem and how can I store the path to where the file is saved in the S3 bucket in my Drawing model?
gem 'aws-sdk', '~> 2'
I have added this instead of gem aws-s3 to my gemfile. Aws-s3 seems a bit old and I understand that aws-sdk is the main gem of Amazon Aws and includes the s3 gem?
Next, following this relevant post, I added to the organizations controller the method upload_file:
def create
@organization = Organization.new(organizationnew_params)
if @organization.save
upload_file(@organization.id)
redirect_to root_url
end
end
private
def upload_file(id)
s3 = Aws::S3::Resource.new(
credentials: Aws::Credentials.new(ENV['S3_ACCESS_KEY'], ENV['S3_SECRET_KEY']), # These environmental variables I had already set for the uploader I have previously created.
region: ENV['AWS_REGION']
)
xmlfile = 'other/graph.xml' # Correct path? This file is located in app/assets/other/graph.xml
directory = "graphs/#{model.class.to_s.underscore}/#{mounted_as}/#{id}"
s3.bucket('mybucketname').object(ENV['S3_ACCESS_KEY']).upload_file(xmlfile)
end
Error message: This current setup generates the error below (referring to the line s3 = Aws::S3::Resource.new). I've of course double checked that I've set heroku config:set AWS_REGION=eu-west-1, which I did. I don't understand the cause of the error.
missing region; use :region option or export region name to ENV['AWS_REGION']
Additional issues:
- I would like to give the file a custom name: "graph#{id)". How to specify this?
- I would like the method to save to the directory in the S3 bucket that I specified in the private method. How to do this?
- I established a 1:1 relationship between the model Drawing and the model Organization. Drawing contains 2 variables:
organization_idandfile_path.File_pathshould include the string to the file that we will save to the S3 bucket at signup. How to create the association betweenfile_pathin the Drawing model and the uploaded file in the S3 bucket?
Aucun commentaire:
Enregistrer un commentaire