我正在使用 Ruby on Rails 制作 RESTful API。我使用 Active Storage 来管理附件。但是,Active Storage 公开提供附件,而我想私下提供服务。
我一直在考虑在像
/assets/:name?token=TOKEN
这样的路线上为他们提供服务。
所以我可以在前端以这种方式管理它们,例如:
// Front-end
const flowerPhoto = new Image
const params = new URLSearchParams({ token })
image.src = `${API_URL}/assets/flower-photo?${params.toString()}`
我怎样才能实现这个目标?
我试过这样:
# config/routes.rb
Rails.application.routes.draw do
scope 'assets/:name', as: 'asset' do
root 'assets#show', as: ''
end
end
# app/models/asset.rb
class Asset < ApplicationRecord
has_one_attached :document
end
# app/controllers/assets_controller.rb
class AssetsController < ApplicationController
include ActiveStorage::SetCurrent
before_action :set_asset
before_action :authorize
def show
redirect_to @asset.document.url
end
private
def set_asset = @asset = Asset.find_by!(name: params[:name])
def authorize = user_authentication(params[:token])
end
# config/application.rb
module App
class Application < Rails::Application
# Public attachment URLs
config.active_storage.draw_routes = false
end
end
尽管如此,我还是收到了这个错误:
NoMethodError in AssetsController#show
undefined method `rails_disk_service_url' for module
redirect_to @asset.document.url
删除已设置的配置,然后:
redirect_to @asset.document.url(expires_in: 5.minutes, disposition: 'inline')