LoginSignup
2
1

More than 3 years have passed since last update.

rails active_storage: install実行時に追加されるテーブルについて

Last updated at Posted at 2020-05-31

active_storage使用時に作成されるテーブルとカラムの役割について自分なりにまとめてみました

参考

環境

  • Rails 5.2.4
  • PostgreSQL
  • Tweetモデルにactive_storageでtweet_imageを追加したとする
  • 同様に、Userモデルにprofile_imageを追加

$ rails dbconsoleを使ってDBの中身を見ていきます

select * from Tweet

 id | content |         created_at         |         updated_at         
----+---------+----------------------------+----------------------------
  1 | first   | 2020-05-31 09:15:39.315909 | 2020-05-31 09:15:39.34726
  2 | second  | 2020-05-31 09:41:35.573983 | 2020-05-31 09:42:03.209896

各テーブルについて

active_storage_blobs

画像データを保存するためのテーブル

select * from active_storage_blobs;

 id |           key            |                      filename                       | content_type |              metadata               | byte_size |         checksum         |         created_at         
----+--------------------------+-----------------------------------------------------+--------------+-------------------------------------+-----------+--------------------------+----------------------------
  1 | g8VoNYkesyKi779tsSdQ2q2W | first_image.jpg                                     | image/jpeg   | {"identified":true,"analyzed":true} |      8237 | zcwCqc6RTr8QFI4elbnF+w== | 2020-05-31 09:15:39.270823
  2 | uzRSGT69i5cNhoWDdoQ2gu8C | second_image.jpg                                    | image/jpeg   | {"identified":true,"analyzed":true} |   2481215 | m5LFOmNS4v3ddFGrtN/byA== | 2020-05-31 09:42:03.191085
  3 | 9o2qkgbC77MixCiYKc3thCdx | user_image.jpg                                      | image/png    | {"identified":true,"analyzed":true} |    254885 | 0+RUqCki1Yn4sZB1ZjpJCw== | 2020-05-31 19:02:28.999065

active_storage_attachment

使うモデルのクラス名を保存するポリモーフィックjoinテーブル

select * from active_storage_attachments;

 id |    name      | record_type | record_id | blob_id |         created_at         
----+--------------+-------------+-----------+---------+----------------------------
  1 | tweet_image  | Tweet       |         1 |       1 | 2020-05-31 09:15:39.324196
  2 | tweet_image  | Tweet       |         2 |       2 | 2020-05-31 09:42:03.199872
  3 | profile_image| User        |         1 |       3 | 2020-05-31 19:02:29.025411
  • name
    • 紐づけるモデルの画像用カラム
  • record_type
    • 紐づけるモデル名
  • record_id
    • record_typeのモデルのid
  • blob_id
    • active_storage_blobsに保存された画像のid

name, record_type, record_idでモデルと画像カラムを決めて、blob_idで画像を紐づけることで一意な画像投稿機能ができると考えています

最後に

おかしい部分があればご指摘いただけると嬉しいです!

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