まとめ
ActiveStorage::BlobsController
の該当アクションを上書きする
コード例
devise
入りなので user_signed_in?
とか current_user
とか使ってるけど、そこは良しなに読み替えてほしい
# config/routes.rb get "/blobs/:signed_id/*filename" => "blobs#show", as: :authenticated_blob_path
# application_helper.rb module ApplicationHelper def authenticated_blob_path(blob, **options) route_for(:authenticated_blob_path, blob.signed_id, blob.filename, options) end end
# brobs_controller.rb class BlobsController < ActiveStorage::BlobsController def show unless user_signed_in? flash[:alert] = "ログインしてね" redirect_to root_path and return end super end end
# view/xx.slim - link_to "ダウンロード", authenticated_blob_path(@xxx.file, disposition: "attachment")
ActiveStorage側が何をしているか
rails/blobs_controller.rb at master · rails/railsで実際のダウンロード処理をしているので、それを上書きする。
rails_blob_path
とかは実際rails/routes.rb at master · rails/railsで定義されているので、それをまるっとパクった形になる。