Upload file to S3 using Active Storage
Goal: create an image model and upload images to Amazon S3 using Active Storage with Rails 5.2.
- Run rails new image-lib to create a rails project
- Run rails active_storage:install
- Run rails g model Image description:string to create image model
- Run rails db:migrate to create tables for image model and active storage
- Update Image model to have a file at /app/models/image.rb:
- Run rails g controller image new index create to create Image controller with new, index and create actions
- Update new view with a form at /app/views/image/new.html.erb
- Update new and create controller at /app/controllers/image_controller.rb
- Update new view at /app/views/image/index.html.erb to display list of images and its description
- Update index controller at /app/controllers/image_controller.rb
Check point: you should be able to upload a file at /image/new and see the image at /image/index. Now you’re able to save the file locally, next step is to upload these images to Amazon S3
Configure storage target to Amazon S3
- Go to config/storage.yml and comment out amazon section
- Update region and bucket name. You can find these information in our Amazon S3 account:
- Add Amazon s3 SDK in your Gemfile, install the gem
- Create AWS IAM user that has permissions: s3:ListBucket, s3:PutObject, s3:GetObject, and s3:DeleteObject
- Run EDITOR=VIM rails credentials:edit to decrypted credentials.yml.enc and update access key id and secret access key
- uncomment AWS section, and enter proper access_key_id and secret_access_key for the AWS IAM user
- Change your development storage service to use S3 at /config/environments/development.rb
Check point: you should be able to upload a file at /image/new, and these files should upload to your AWS S3 bucket
Useful links: