0
0

More than 1 year has passed since last update.

Active Storageのしくみ

Posted at

Ruby on Railsにて、Active Storageのインストール後に生成されるマイグレーションファイルの中身が気になったので、その仕組みを読み解いてみる。

〜Active Storage の導入コマンド〜

$ rails active_storage:install

$ rails db:migrateで、Active Storageが使えるようになる。

マイグレーションファイルに定義される3つのテーブル

  1. active_storage_blobsテーブル
  2. active_storage_attachementsテーブル
  3. active_storage_variant_recordsテーブル

active_storage_blobsテーブル

  • ActiveStorage::Blobモデルのテーブル
  • 添付されたファイルに対応
  • 識別key(:key)、ファイル名(:filename)、Content-Type(:content_type)、ファイルのメタデータ(:metadata)、サイズ(:byte_size)などを管理

active_storage_attachementsテーブル

  • ActiveStorage::Attachmentモデルのテーブル
  • ActiveStorage::Blobモデルとアプリ内のモデルを関連付ける中間テーブル
  • 関連付けるモデルのクラス名(:record_type)や連携するFKカラム名(:name)を、FK値(:record_id)と共に保持。
  • ポリモーフィック関連付けがされている。
    • t.references :record, polymorphic: trueとすることで、record_typerecord_idが自動生成される
    • メリット:ファイルがアップロードされるたびにactive_storage_attachementsテーブル&ActiveStorage::Attachmentモデルを更新する必要がなくなる
  • 疑問点
    なぜt.references :record, polymorphic: true, index: falseとココではindexを付与せずに、下記のように後でindexを追加しているのか?
t.index [ :record_type, :record_id, :name, :blob_id ], name: :index_active_storage_attachments_uniqueness, unique: true

 →複合キーを作っている。関連づけるモデルのクラス名(:record_type)、そのモデルのFKカラム名(:name)、FK値(:record_id)、BlobモデルのFK値(:blob_id)を合わせた複合キーを作ることで、中間テーブルの役目を果たせる。

active_storage_variant_recordsテーブル

  • ActiveStorage::Variantモデルのテーブル
  • サイズの変更などの加工情報を記録する

参考

0
0
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
0
0