Rails5.2の新しい機能の中にActive Storageというものが気になったので使ってみた。
Active Storageとは
AWS S3やGoogle Cloud Storageなどのクラウドファイルストレージサービスへのアップロードをシンプルにやってくれる仕組みとのこと。
もちろん物理的なディスクシステムへ保存することもできるけど、主眼はあくまでクラウドサービスに置いているらしい。
Modelの仕組
Active Storageをインストールするとactive_storage_blobs,active_storage_attachmentsが生成される。
active_storage_blobsはmetadata (filename, content-type, etc.)を保存するtableになっている。keyカラムはidentifier keyとしてクラウドファイルストレージのアップするファイルのfilenameになる。

active_storage_attachmentsは添付ファイルの親モデルとactive_storage_blobsをアソシエートしてくれる。親モデルはpolymorphicになる。

使い方
- 環境
- Rails 5.2.0.beta2
- ruby 2.4.1p111
インストール
rails newを通してプロジェクトを作成するとき自動的にActive Storageがインストールされる。
rails new --skip-active-storageにするとインストールせずにプロジェクトを作成できる。
既存プロジェクトにActive Storageを入れたい場合は、まずRailsのバージョンをアップグレードしてから、
1 2 | |
で入れることができる。
サンプルコード
- gemfile
1 2 | |
- model
1 2 3 4 | |
- controller
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | |
- view
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | |
クラウド設定
- config/environments/development.rb
1 2 | |
- config/storage.yml
1 2 3 4 5 6 7 | |
リサイズ
1
| |
このようにvariantメソッドを使えばリサイズでビューに表示できる。
参照:https://github.com/rails/rails/blob/master/activestorage/app/models/active_storage/variant.rb
Direct upload
JSを使ってDirect uploadすることもできる。
include activestorage.js
- asset pipelineの場合
//= require activestorage- npm packageの場合
import * as ActiveStorage from "activestorage" ActiveStorage.start()file_fieldに設定
- ビューの file_field に direct_upload: true を入れる
= f.file_field :avatar, direct_upload: true
サンプル
https://active-storage-jo.herokuapp.com
参考
https://qiita.com/nashirox/items/e63fd28d974ecf12f0e7
https://github.com/rails/rails/tree/master/activestorage