在 Rails 中使用 Active Storage 时缺少主机问题

Missing host problem when using Active Storage in Rails

我不希望我们的服务器被触及的次数超过需要(我们正在为此目的使用 CDN)我想使用直接 link 资源(没有活动存储重定向)

直接link可以通过

检索
object.active_storage_file.service_url

但这会导致错误:

Missing host to link to! Please provide the :host parameter, set default_url_options[:host], or set :only_path to true

env/development.rb 我已经添加了 :

Rails.application.routes.default_url_options[:host] = "localhost:3000"

但这并不能解决问题。知道为什么以及如何做到这一点吗?

在你的控制器中你可以写:

before_action do
   ActiveStorage::Current.host = request.base_url
end

这样您就可以使用 say:

向主机提供服务 url
active_storage_file.blob.service_url if active_storage_file.attached?