rails-activestorage - ActiveStorage service_url && rails_blob_path 在不使用 S3 时无法生成完整的 url
问题描述
我有一个基本的 ActiveStorage 设置,其中一个模型是has_many_attached :file_attachments
. 在其他地方的服务中,我试图生成一个在主应用程序(电子邮件、工作等)之外使用的链接。
使用生产中的 S3,我可以做到:
item.file_attachments.first.service_url
并且我获得了指向 S3 存储桶+对象的适当链接。
我不能使用导轨中规定的方法: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
在此处设置主机也不会生成完整的 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
并指定主机无济于事:
item.file_attachments.first.service_url(host:'http://localhost.com')
ArgumentError: unknown keyword: host
我也试过添加
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'
没有成功。
我的问题是 -我怎样才能以在开发和生产中都有效的方式获取完整的 URL?或者我在哪里设置主机?
解决方案
Active Storage 的磁盘服务希望在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
在控制器之外,用于ActiveStorage::Current.set
提供主机:
ActiveStorage::Current.set(host: "https://www.example.com") do
item.file_attachments.first.service_url
end
推荐阅读
- javascript - 我有 nodejs 子进程的执行流程问题
- typescript - 打字稿省略助手不允许覆盖属性
- teradata - 如何在没有毫秒的情况下获取 Teradata SQL 时间戳
- node.js - 如何在 node.js 应用程序中对控制器进行单元测试?
- node.js - NodeJS 服务层异步通信
- angular - Angular Route Change 破坏了 Observables 的组件服务关系
- c# - 在 Startup.cs 中使用 .AddGoogle() 时如何在 Web 应用中构建 GmailService?
- metamask - Metamask 无法在私有仲裁区块链中执行正常交易
- c# - 如何正确使用 FileStream.ReadAsync 不阻塞 UI
- c++ - 使用 aruco 和 opencv4 的未解析符号