LoginSignup
1
2

More than 3 years have passed since last update.

Active Storageの概要

Last updated at Posted at 2021-03-23

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

上記テーブルが、データベースに追加されていれば成功:v:

2. Active Record モデルの用意

ファイルアップロード機能を使いたいモデルを用意する。(ここではtweetモデルにしておきます)
画像用のカラムを用意する必要がない点もActive Storageの特徴の一つ:eyes:

3.ファイルの添付

3-1) 1つの添付ファイルの場合

Tweetモデルに1つの画像を添付するには、has_one_attachedを使う。

tweet.rb
class Tweet < ApplicationRecord
  has_one_attached :image
end
tweets_controller.rb
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を追記して、複数ファイルの選択を許可する。

tweet.rb
class Tweet < ApplicationRecord
  has_many_attached :images
end
tweets_controller.rb
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

new.html.erb
<%= 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 で定義された保存先の名前。(保存先の変更については別の記事で記載したいと思います:zzz:

参考

https://railsguides.jp/active_storage_overview.html
https://qiita.com/hmmrjn/items/7cc5e5348755c517458a

1
2
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
2