To start using Active Storage, you need to run a command in our Whales terminal to create the tables that Rails will use to keep track of your attachments:
rails active_storage:install
Psst... this creates a migration. Make sure to run them after!
Head into config/storage.yml
and drop the following configuration into it — this is our Amazon S3 bucket, which your files will go into on upload:
amazon:
service: S3
access_key_id: AKIAJD2BGWTLG35SIRNA
secret_access_key: UdJED8qTNm+rAhA4LPi+q3AD0a49azPZsTHw1KXu
region: us-west-2
bucket: rails-decal-demo
Next, jump into config/environments/development.rb
and edit this line (should be set to :amazon
instead of :local
:
- config.active_storage.service = :local
+ config.active_storage.service = :amazon
Add the following to your Gemfile
:
gem 'aws-sdk-s3'
And run bundle install
in your terminal.
You will need to restart your Rails server at this point.
Allowing files to be attached to models is surprisingly easy. We can simply specify the following inside of app/models/post.rb
:
has_one_attached :photo
Because files are stored on a database table that Rails manages, this change will only affect our model and not our schema/migrations.
One quick thing we'll have to adjust in our scaffold is allowing the photo as a new parameter in our form (which we'll add below).