Active Storageとは?
5.2でRailsで実装されたgemでクラウドストレージサービス(AWSのs3、Google Colud Storage、Microsoft Azure Storage)へファイルをアップロードしてActiveRecordでモデルに紐付けるということが簡単にできるようになりました。もちろん、開発環境ではローカル、本番環境のみ外部ストレージサービスを使うと言ったような使い方がデフォルトでできるようになっています。
扱えるファイルの種類
どんな種類のファイルでも扱えます。
機能詳細
- 画像についてはサイズや形式変換を行える。
- ビデオやPDFについてはプレビュー機能も提供している。
Active Storageで実装する。
下記コマンドを実施します。
1 |
rails active_storage:install |
すると下記のようにdb/migrate/xxxx_create_active_storage_tables.active_storage.rbにマイグレーションファイルが作成されています。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
# This migration comes from active_storage (originally 20170806125915) class CreateActiveStorageTables < ActiveRecord::Migration[5.2] def change create_table :active_storage_blobs do |t| t.string :key, null: false t.string :filename, null: false t.string :content_type t.text :metadata t.bigint :byte_size, null: false t.string :checksum, null: false t.datetime :created_at, null: false t.index [ :key ], unique: true end create_table :active_storage_attachments do |t| t.string :name, null: false t.references :record, null: false, polymorphic: true, index: false t.references :blob, null: false t.datetime :created_at, null: false t.index [ :record_type, :record_id, :name, :blob_id ], name: "index_active_storage_attachments_uniqueness", unique: true t.foreign_key :active_storage_blobs, column: :blob_id end end end |
Active Storageでは下記2つのテーブルを利用します。
- active_storage_blobs
- active_storage_attachments
active_storage_blobs(「ActiveStorage::Blob」というモデルに紐づく)
添付されたファイルに対応するモデルです。ファイルの実体をDB外で管理することを前提としています。
active_storage_attachments(「ActiveStorage::Attachment」というモデルに紐づく)
「ActiveStorage::Blob」とアプリ内の様々なモデルを関連づける中間的な立ち位置のモデルになります。他のアプリ内の様々なモデルと紐付けれるように関連するモデルのFKカラム名(外部キー)をFK値として保持します。なお、ActiveStorage::Blobとは直接IDのみで紐付けます。
下記コマンドを実施して上記の2テーブルをDBに反映します。
1 |
rails db:migrate |
Active Storageの設定をする。
保存場所の設定
config/environments/development.rb
ファイルを管理する場所の設定が「local」になっていることを確認できます。localは「config/storage.yml」にて場所が設定されています。
1 2 |
# Store uploaded files on the local file system (see config/storage.yml for options) config.active_storage.service = :local |
config/storage.yml
下記がlocalの設定になります。
1 2 3 |
local: service: Disk root: <%= Rails.root.join("storage") %> |
Railsアプリが配置されたディレクトリ配下のstorageというディレクトリにファイルを保存する設定になっています。
モデルの設定
app/models/モデル名.rb
1 2 3 4 |
class モデル名 < ApplicationRecord has_one_attached :image ★ ‥ end |
「has_one_attached」というメソッドで1つのタスクに1つの画像を紐づけることができます。
ビューファイル側の設定
アップロード側の設定
form_withであれば下記のように「image」という画像アップロード用の入力部品を設定します。
1 2 3 4 |
= form_with model: @モデル名, local: true do |f| .form-group = f.label :image = f.file_field :image, class: 'form-control' |
表示側の設定
1 |
image_tag @オブジェクト変数.image if @オブジェクト変数.image.attached? |
「image_tagビューヘルパー」を使って画像を表示させましょう。なお、画像オブジェクトがない場合も対応できるように「if @オブジェクト変数.image.attached?」という文を付け加えて確認するようにしましょう。
コントローラーの設定
1 |
params.require(:モデル名).permit(:カラム1,:カラム2, :image★) |
Strong Parameterによって画像アップロードも許可されます。
この記事へのコメントはありません。