Active Storageについて
ファイルアップロード機能を簡単に実装できる機能(Gem)。Railsに統合されているため、指定のコマンドを実行することで簡単に導入できる。
Amazon S3, Google Cloud Storage, Microsoft Azure Storageなどのクラウドストレージサービスに対するファイルのアップロードを簡単に行うことができる。クラウドストレージの他に、ローカルディスクにファイルを保存することもできる。
Active Storage 使い方
1. Active Storageをインストール
Active Storageをアプリケーション内で使用するための準備として、以下コマンドを実行する。
rails active_storage:install
上記コマンドを実行すると、Active Storageに関連したマイグレーションが作成されるのでマイグレートし、
- active_storage_attachments
- active_storage_blobs
上記テーブルが、データベースに追加されていれば成功
2. Active Record モデルの用意
ファイルアップロード機能を使いたいモデルを用意する。(ここではtweetモデルにしておきます)
画像用のカラムを用意する必要がない点もActive Storageの特徴の一つ
3.ファイルの添付
3-1) 1つの添付ファイルの場合
Tweetモデルに1つの画像を添付するには、has_one_attachedを使う。
class Tweet < ApplicationRecord
has_one_attached :image
end
class TweetsController < ApplicationController
(省略)
def create
@tweet = Tweet.new(tweet_params)
if @tweet.save
redirect_to root_path
else
render 'new'
end
end
(省略)
private
def tweet_params
params.require(:tweet).permit(:image, :text).merge(user_id: current_user.id)
end
end
3-1) 複数の添付ファイルの場合
Tweetモデルに1つの画像を添付するには、has_many_attachedを使う。
フォームのfile_fieldにmultiple: trueを追記して、複数ファイルの選択を許可する。
class Tweet < ApplicationRecord
has_many_attached :images
end
class TweetsController < ApplicationController
(省略)
def create
@tweet = Tweet.new(tweet_params)
if @tweet.save
redirect_to root_path
else
render 'new'
end
end
(省略)
private
def tweet_params
params.require(:tweet).permit(:images, :text).merge(user_id: current_user.id)
end
end
<%= form_with model: @tweet, local: true do |f| %>
<%= f.file_field :images, multiple: true %>
<%= f.text_area :text %>
<%= f.submit %>
<% end %>
4. ファイルの保存先
ファイルの保存先は、各環境の設定ファイルに記載する。
初期状態では、開発環境(development)、本番環境(production)ともに保存先は :local に設定されている。この local とは、 config/storage.yml で定義された保存先の名前。(保存先の変更については別の記事で記載したいと思います)
参考
https://railsguides.jp/active_storage_overview.html
https://qiita.com/hmmrjn/items/7cc5e5348755c517458a