--- title: Active storage AWS S3 上傳大頭照 tags: AWS S3 --- [官網文件](https://guides.rubyonrails.org/active_storage_overview.html) -------------------------------------------------- ### 1. 安裝 active_storage - rails active_storage:install - rails db:migrate ![](https://i.imgur.com/ag05jwR.png) ### 2. Config / storage.yml 把註解打開(amazon - bucket) ![](https://i.imgur.com/40qQg4f.png) ![](https://i.imgur.com/ZHsiqH4.png) ### 到 [aws 註冊](https://aws.amazon.com/tw/s3/) -> ### 建立儲存貯體 -> 填寫名稱、選擇鄰近的區域 -> 捲到最下方選建立儲存貯體 -> 取得 region, bucket ![](https://i.imgur.com/7L9lvJS.png) ![](https://i.imgur.com/VssDAZw.png) ### 建立新的存取金鑰 -> 取得 - 存取金鑰 ID (access_key_id) - 私密存取金鑰 (secret_access_key) ![](https://i.imgur.com/luamZT2.png) ### 3. Config / environments / development.rb & production.rb 裡的 config.active_storage.service 設定為 :amazon - 因為是使用aws s3 來儲存檔案,所以development.rb 須設定為:amazon ![](https://i.imgur.com/k9AZrOP.png) ### 4. 安裝 aws-sdk-s3 [aws-sdk-s3 的文件](https://github.com/aws/aws-sdk-ruby) ![](https://i.imgur.com/IgNDgMj.png) ### 5. user.rb 加上 has_one_attached :avatar,每位使用者有一張大頭貼 ![](https://i.imgur.com/9iXwLeg.png) ![](https://i.imgur.com/XRejK7M.png) ### 6. edit.html.erb 加上 <%= f.file_field :avatar %>,讓選擇大頭貼按鈕有上傳檔案功能 ![](https://i.imgur.com/5JADTxf.png) ![](https://i.imgur.com/FsS6TMh.png) ### 7. registrations_controller.rb 把 :avatar 加入白名單 ![](https://i.imgur.com/ajfyt5c.png) ![](https://i.imgur.com/MeT4Yuk.png) ### 8. 判斷使用者的頭像,有上傳的話就顯示該頭像,沒有的話就顯示預設的頭像 ![](https://i.imgur.com/aexKE9O.png) ![](https://i.imgur.com/mq4e1CC.png)