Best way is using a concentrating model, like you mentioned, and creating a custom controller.
Model:
class Attachment < ApplicationRecord
belongs_to :record, polymorphic: true
has_one_attached :file
end
Route:
get "files/:id/:filename", to: "attachments#show"
Controller
class AttachmentsController < ActiveStorage::Blobs::ProxyController
private
def set_blob
@blob = Attachment.find(params[:id]).file.blob
end
end
If you don’t want to do that, then your second option works (as long as you are using has_one_attached instead of has_many_attached):
Route:
get "files/:model/:id/:filename", to: "attachments#show"
Controller
class AttachmentsController < ActiveStorage::Blobs::ProxyController
private
def set_blob
@blob = params[:model].classify.find(params[:id]).file.blob
end
end
PS: If you are using has_many_attached, don’t. It’s almost never worth it.