【问题标题】:Setting ActiveStorage host设置 ActiveStorage 主机
【发布时间】:2019-04-09 19:55:33
【问题描述】:

现在我有一个设置,允许用户使用 CNAME 将他们的应用程序直接指向我的 Rails 应用程序(又名,将 www.example.com 指向我在 www.example2.com 托管的应用程序)。

一切都很好!但是,我想使用我的应用程序www.example2.com 作为主机来提供图像(出于 CDN 的原因)。

似乎 ActiveStorage 正在默认(并强制...)主机成为当前主机,并且不允许我更改它。

我有:

config.action_controller.asset_host = 'https://www.example2.com'
    Rails.application.routes.default_url_options[:host] = 'https://example2.com'

它适用于静态资产!但是,ActiveStorage image_tag 仍在使用正在查看站点的任何域,在本例中为 www.example2.com

关于如何让它始终使用asset_host服务的想法?

【问题讨论】:

  • 有什么解决办法吗?我也面临同样的问题...
  • @Tintin81 不幸的是,没有,我最终不再使用image_tag,而是使用环境变量为img 标签设置了我自己的主机。叹息。

标签: ruby-on-rails rails-activestorage


【解决方案1】:

使用ActiveStorage::Current.host,它使用CurrentAttributes,这是一种在每次请求时设置/重置的属性,可以在Rails应用程序的任何地方使用:

class ApplicationController
  before_action do
    ActiveStorage::Current.host = 'https://example2.com'
  end
 end

如果您想在控制器之外使用它,请使用ActiveStorage::Current.set 提供主机:

ActiveStorage::Current.set(host: "https://www.example2.com") do
  item.file_ttachments.first.service_url
end

Rails 参考文档:https://edgeapi.rubyonrails.org/classes/ActiveStorage/SetCurrent.html

【讨论】:

    猜你喜欢
    • 2017-08-12
    • 1970-01-01
    • 2011-01-13
    • 1970-01-01
    • 2013-07-16
    • 2013-03-15
    • 2014-07-15
    • 2013-12-09
    • 2014-09-20
    相关资源
    最近更新 更多