【问题标题】:Missing host to link to error in Rails 5.2.1缺少主机以链接到 Rails 5.2.1 中的错误
【发布时间】:2019-07-30 00:01:22
【问题描述】:

我已经解决了有关此错误的所有 stackoverflow 问题: https://duckduckgo.com/?q=rails+Missing+host+to+link+to

所有帖子都提到了相同的解决方案,即在您正在处理的环境文件中添加配置。就我而言,我添加到了我的 development.rb:

config.active_storage.service = :local
config.action_mailer.default_url_options = { host: "localhost", port: "3000" }
MyApp::Application.default_url_options = Robson::Application.config.action_mailer.default_url_options
Rails.application.routes.default_url_options = Robson::Application.config.action_mailer.default_url_options

但我仍然收到臭名昭著的错误消息:

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

如果我尝试打开本地上传的文件,请在以下位置:

 open(file.service_url)

或者如果我尝试从 ActiveAdmin 访问文件(我将模型称为“附件”并且我正在使用 ActiveStorage)

column(:file) {|a| link_to a.file.filename, a.file.service_url}

我还尝试将字典中的“host”设置为上述“link_to”和“open”函数中的参数。我也试过“only_path”。

没有任何作用。

任何帮助将不胜感激!

P.S.:我的活动存储配置:

local:
  service: Disk
  root: <%= Rails.root.join("storage") %>

test:
  service: Disk
  root: <%= Rails.root.join("tmp/storage") %>

amazon:
  service: S3
  access_key_id: S3_ACCESS_KEY_ID
  secret_access_key: S3_SECRET_ACCESS_KEY
  bucket: S3_BUCKET
  region: S3_REGION

更新

尝试使用 rails_representation_url 但收到错误ActiveStorage::Attached 的未定义方法“变体”

class Attachment < ApplicationRecord
  include Rails.application.routes.url_helpers
  has_one_attached :file
....
def with_uploaded_file
  tempfile = Tempfile.open([file.filename.to_s, File.extname(file.filename.to_s)]) do |file_temp|
  file_temp.binmode unless file.content_type =~ /text/
  require 'open-uri'
  # file_temp.write(open(file.service_url).read)
  file_temp.write(open(rails_representation_url(file, only_path: true)).read)
  file_temp
end
begin
  yield(tempfile)
ensure
  tempfile.unlink
end

【问题讨论】:

    标签: ruby-on-rails rails-activestorage


    【解决方案1】:

    我将 Rails 从 5.1 升级到 5.2 并且遇到了同样的问题。

    解决方案:https://github.com/rails/rails/issues/32866

    所以当你有你的 ActiveRecord 变体而不是

       variant.service_url
    

        rails_representation_url(variant, only_path: true)
    

    【讨论】:

    • 感谢您的回答。我试过这个,但我得到以下错误。我更新了问题中的代码,以准确地向您展示我是如何使用您的答案的。 undefined method 'variation' for #&lt;ActiveStorage::Attached::One:0x000055f7a78d9b50&gt;
    • @anode84 我注意到错误消息提到了variation这个词,但应该使用的方法是variant
    猜你喜欢
    • 2017-11-08
    • 1970-01-01
    • 1970-01-01
    • 2013-11-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-18
    • 2016-07-08
    相关资源
    最近更新 更多