rails-activestorage - ActiveStorage service_url && rails_blob_path 在不使用 S3 时无法生成完整的 url

标签 rails-activestorage

我有一个基本的 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 中找到用于生成 URL 的主机。 .
当您调用 ActiveStorage::Blob#service_url手动,确保 ActiveStorage::Current.host已设置。如果你从 Controller 调用它,你可以继承 ActiveStorage::BaseController .如果这不是一个选项,请设置 ActiveStorage::Current.hostbefore_action钩:

class Items::FilesController < ApplicationController
  before_action do
    ActiveStorage::Current.host = request.base_url
  end
end
在 Controller 之外,使用 ActiveStorage::Current.set提供主机:
ActiveStorage::Current.set(host: "https://www.example.com") do
  item.file_attachments.first.service_url
end

关于rails-activestorage - ActiveStorage service_url && rails_blob_path 在不使用 S3 时无法生成完整的 url,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51110789/

相关文章:

ruby-on-rails - ActiveStorage - 获取模型中的变体 URL

ruby-on-rails - Rails Active Storage 并非每次都有效。有时有效,有时无效

ruby-on-rails - 事件存储 - 添加文件描述/文本 - Ruby on Rails 5.2

ruby-on-rails - ActiveStorage 不会裁剪变体

ruby-on-rails - 事件存储视频的 Rails 预览不起作用

ruby-on-rails - 如何将 has_one_attached 转换为 has_many_attached 到带有 has_one 附件的现有表?

ruby-on-rails - Rails API ActiveStorage : Get Public URL to display image from AWS S3 Bucket?

ruby-on-rails - 更改 ActiveStorage Controller 路径

amazon-s3 - Rails 5.2 Active Storage直接上传失败: CORS header ‘Access-Control-Allow-Origin’ missing