回上一頁

Rails Active Storage檔案上傳&技術筆記

Rails Active Storage檔案上傳技術

Rails5.2以上的產物

 

Model設定: 

has_one_attached :logo

has_many_attached :images

 

它Model在有兩種設定方式,一對一 or 一對多

config設定檔 active_storage.rb 是官方文件名稱,可以做一些有需要自訂需求。

 

使用這個table會將檔案存在 active_storage_attachments & active_storage_blobs 兩張表裡面:

schema.rb



 create_table "active_storage_attachments", id: :uuid, default: -> { "gen_random_uuid()" }, force: :cascade do |t|
    t.string "name", null: false
    t.string "record_type", null: false
    t.uuid "record_id", null: false
    t.uuid "blob_id", null: false
    t.datetime "created_at", null: false
    t.index ["blob_id"], name: "index_active_storage_attachments_on_blob_id"
    t.index ["record_type", "record_id", "name", "blob_id"], name: "index_active_storage_attachments_uniqueness", unique: true
  end

  create_table "active_storage_blobs", id: :uuid, default: -> { "gen_random_uuid()" }, force: :cascade 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"], name: "index_active_storage_blobs_on_key", unique: true
  end

 

Views:

如果是一對多,在Views裡要使用迴圈(陣列的方式)取得,一對一則就直接撈出來即可。

 

 

參考資料:

官方文件 https://guides.rubyonrails.org/v6.0.0/active_storage_overview.html