Rails ActionStorage with s3
To create a new application: rails new activeStorageTrial
Then enter the folder using cd activeStorageTrial/
Then scaffold a basic application using rails g scaffold imagebox title caption:text
Then migrate the changes using rails db:migrate
At this point you will able to create a post with title and caption, but we need to upload images to our storage
So we will install active storage in our application rails active_storage:install
The migrate the changes again rails db:migrate
Then change imagebox_params in /views/app/imageboxes/_form.html to accept the image
To models/imagebox.rb add the following inside class Imagebox
To take image as input add the following code to app/views/_form.html.erb
This will allow us to upload images to our storage. Now to view them using show page, we will do the following
Next, we will try to upload the image to an s3 bucket
Go to aws console and create an s3 bucket
Then create a policy with following permissions:
s3:ListBucket, s3:PutObject, s3:GetObject, and s3:DeleteObject
In resources tab, add bucket name that this policy should apply to.
Next we will create a user
While creating user give it a name and check programmatic access. Then select the policy they you just created.
download the csv and save it.
In config/storage.yml
In this change the access_key_id, secret_access_key, region and bucket to your aws settings.
In config/production.rb change the active storage configuration from local to amazon config.active_storage.service = :amazon
Then to edit our credentials, we use the following command EDITOR=nano rails credentials:edit
TO check this, we will deploy this app to production. First we need to change database from sqlite to posstgres
So, in gemfile remove gem 'sqlite'
and add gem 'pg'
add the following to database.yml and then remove the previous configuration.
The run bundle
and change username to your username
Then run the following commands in terminal rake db:setup
rake db:migrate
from boot.rb remove require bootsnap
remove the gemfile.lock file remove gem bootsnap
from the gem file bundle install
line, because it creates problems with heroku deployment. If there is still a problem, downgrade bundle from 2.2.9 to 2.1.4(as of 16 feb 2021)
Then run git add
git commit -m "your message"
Then create a heroku app using heroku website and follow the instructions on heroku website to deploy the app to heroku.