LoginSignup
1
3

More than 3 years have passed since last update.

Heroku+ActiveStorage+Amazon S3

Last updated at Posted at 2020-10-10

1 AWSコンソール → サービス → ストレージ → S3でパケット作成

項目 入力・選択
パケット名 ex: my-rails-app-first-bucket
リージョン :flag_jp: 東京
アクセス権限 チェック欄全てoff
上記以外 デフォルト

2 アクセスキーを作る
下記参照
https://tech-blog.s-yoshiki.com/entry/135

3 必要なGemのインストール

gem "aws-sdk-s3", require: false #追記

4 S3へのアクセスキーを入力

$ EDITOR=vim rails credentials:edit

# コメントアウトを解除する
aws:
 access_key_id: #ここに自分のアクセスキーIDをコピペ
 secret_access_key: #ここに自分のシークレットアクセスキーをコピペ

-vi/vim操作-
iキーで編集開始、escで編集終了 、 ZZで保存して終了
後から入力を確認したいときは

$ rails credentials:show

5 Herokuでの画像の保存先をAmazon S3に変更

config/storage.yml
amazon:
  # 以下3行はそのまま
  service: S3
  access_key_id: <%= Rails.application.credentials.dig(:aws, :access_key_id) %>
  secret_access_key: <%= Rails.application.credentials.dig(:aws, :secret_access_key) %>
  # 以下2行は変える
  region: ap-northeast-1 #東京
  bucket: my-rails-app-first-bucket #自分で作成したS3のバケットの名前
config/environmentas/production.rb
config.active_storage.service = :amazon #amazonに変更

6 最後にHerokuでやること

$ heroku buildpacks:add -i 1 https://github.com/heroku/heroku-buildpack-activestorage-preview
$ git add .
$ git commit -m "added s3 to production"
$ git push heroku master

Railsプロジェックトのマスターキー(config/master.keyの中身)をコピーします

$ heroku config:set RAILS_MASTER_KEY=マスターキーをここに貼り付け
$ heroku run rails db:migrate
$ heroku open

-応用編-
ActionTextを使用している場合、S3の方でS3→パケット→アクセス許可→Cross-Origin Resource Sharing (CORS)に行き。CORSを設定する必要がある。

[
    {
        "AllowedHeaders": [
            "*"
        ],
        "AllowedMethods": [
            "PUT",
            "POST",
            "DELETE"
        ],
        "AllowedOrigins": [
            "URL"
        ],
        "ExposeHeaders": []
    }
]
1
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
3