ruby-on-rails - ActiveStorage::Current.host= 已弃用,我如何使用 ActiveStorage::Current.url_options

标签 ruby-on-rails rails-activestorage

我使用 url 方法在 erb 文件中呈现我的事件记录附件的 url。

#controller    
class RecordMetadataController < ApplicationController
        before_action do
        ActiveStorage::Current.host = request.base_url
      end
    .
    .
    .
    end


#view
    <iframe src="<%= file.url expires_in: 30 ,disposition: :inline %>" width="600" height="750" style="border: none;"></iframe>

Rails 在我的控制台中给出了 DEPRECATION WARNING,所以我尝试更新我的代码,但我无法让它工作。

***DEPRECATION WARNING: ActiveStorage::Current.host= is deprecated, instead use ActiveStorage::Current.url_options***

更新代码

#controller
...
ActiveStorage::Current.url_options = request.base_url
...

新错误

在 web 控制台中,我正在尝试获取文件的完整 url

>> file.url
ArgumentError: Cannot generate URL for K01_D01_G12.pdf using Disk service, please set ActiveStorage::Current.url_options.

有人可以帮忙吗?

最佳答案

ActiveStorage::Current.url_options 实际上是一个 Hash,它具有用于 protocolhostport。因此你需要:

before_action do
  ActiveStorage::Current.url_options = { protocol: request.protocol, host: request.host, port: request.port }
end

或者,ActiveStorage 提供了一个关注点 (ActiveStorage::SetCurrent) 来执行此操作。因此,您应该能够执行以下操作:

class RecordMetadataController < ApplicationController
  include ActiveStorage::SetCurrent
  ...
end

关于ruby-on-rails - ActiveStorage::Current.host= 已弃用,我如何使用 ActiveStorage::Current.url_options,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71860516/

相关文章:

ruby-on-rails - 更改belongs_to关联的迁移

ruby-on-rails - Class.new 在这个 Rspec 中有什么好处

ruby-on-rails - Active Record 的 'joins' 方法背后是什么?

ruby-on-rails - 音频标签在 Active admin、Ruby on Rails 中不起作用

ruby-on-rails - 如何使用带有变体的 Imagemagick 命令行选项创建裁剪和居中的图像?

ruby-on-rails - 如何设置 ActiveStorage 以允许公共(public)和私有(private)附件

ruby-on-rails - 如何将文件隐私(公共(public)或私有(private))添加到 rails 中具有事件存储的谷歌云存储文件?

ruby-on-rails - Rails - 用于 session 的 Cookie 或 Active Record 存储

ruby-on-rails - Rails 使用事件存储读取 csv 文件数据

ruby-on-rails - 如何在 ActiveAdmin 中使用 ActiveStorage `has_many_attached` 编辑多个附加图像