不使用S3时,ActiveStorage service_url && rails_blob_path无法生成完整URL

tgf*_*tgf 12 rails-activestorage

我有一个基本的ActiveStorage设置,其中包含一个模型has_many_attached :file_attachments.在其他地方的服务中,我正在尝试生成一个在主应用程序之外使用的链接(电子邮件,工作等).

使用S3生产我可以做到: item.file_attachments.first.service_url我得到了一个到S3 bucket +对象的适当链接.

我无法使用导轨指南中规定的方法: Rails.application.routes.url_helpers.rails_blob_path(item.file_attachments.first)

它错误: ArgumentError: Missing host to link to! Please provide the :host parameter, set default_url_options[:host], or set :only_path to true 我可以传递一个host: 'http://....'参数,它很高兴,虽然它仍然不会生成完整的URL,只是路径.

在开发中我使用磁盘备份文件存储,我不能使用任何一种方法:

> Rails.application.routes.url_helpers.rails_blob_path(item.file_attachments.first)
ArgumentError: Missing host to link to! Please provide the :host parameter, set default_url_options[:host], or set :only_path to true
Run Code Online (Sandbox Code Playgroud)

在此处设置主机也不会生成完整的URL.

在生产service_url工作中,但是在开发中我得到错误:

> item.file_attachments.first.service_url
ArgumentError: Missing host to link to! Please provide the :host parameter, set default_url_options[:host], or set :only_path to true
Run Code Online (Sandbox Code Playgroud)

并指定主机没有帮助:

item.file_attachments.first.service_url(host:'http://localhost.com')
ArgumentError: unknown keyword: host
Run Code Online (Sandbox Code Playgroud)

我也尝试过添加

config.action_mailer.default_url_options = { :host => "localhost:3000" }
config.action_storage.default_url_options = { :host => "localhost:3000" }
Rails.application.routes.default_url_options[:host] = 'localhost:3000'
Run Code Online (Sandbox Code Playgroud)

没有成功.

我的问题是 - 如何以适用于开发和生产的方式获取完整的URL?或者我在哪里设置主机?

Geo*_*orn 18

Active Storage的磁盘服务期望在中找到用于生成URL的主机ActiveStorage::Current.host.

ActiveStorage::Blob#service_url手动呼叫时,确保ActiveStorage::Current.host已设置.如果从控制器中调用它,则可以进行子类化ActiveStorage::BaseController.如果那不是一个选项,请设置ActiveStorage::Current.host一个before_action钩子:

class Items::FilesController < ApplicationController
  before_action do
    ActiveStorage::Current.host = request.base_url
  end
 end
Run Code Online (Sandbox Code Playgroud)

在控制器之外,用于ActiveStorage::Current.set提供主机:

ActiveStorage::Current.set(host: "https://www.example.com") do
  item.file_attachments.first.service_url
end
Run Code Online (Sandbox Code Playgroud)

  • 控制器中的“include [ActiveStorage::SetCurrent](https://github.com/rails/rails/blob/master/activestorage/app/controllers/concerns/active_storage/set_current.rb)”将执行与上面的样本。 (3认同)