首页 文章

在模型中生成图像URL - ActiveStorage

提问于
浏览
1

我有一个使用ActiveStorage(Rails 5.2.0.rc2)的简单模型,模型如下所示:

class Vacancy < ApplicationRecord
  has_one_attached :image

  validates_presence_of :title

  def to_builder
    Jbuilder.new do |vacancy|
      vacancy.call(self, :id, :title, :description, :created_at, :updated_at)
      vacancy.image do
        vacancy.url image.attached? ? Rails.application.routes.url_helpers.url_for(image) : nil
      end
    end
  end
end

然后在 to_builder 方法中我想显示图像的永久URL,我正在按照rails指南(http://edgeguides.rubyonrails.org/active_storage_overview.html#linking-to-files)中的建议尝试使用 Rails.application.routes.url_helpers.url_for(image) 但它引发了这个错误:

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

在我的应用程序中,我已经设置了 default_url_options[:host] 但是它不起作用,即使写入 url_for(image, host: 'www.example.com')url_for(image, only_path: true) 也不起作用,因为它引发了另一个错误: wrong number of arguments (given 2, expected 1)

使用activestorage在模型范围中显示永久URL的正确方法是什么?

2 回答

  • 0

    url_for typicaly需要一个选项哈希,如果你传入一个模型,你将无法提供 host 选项:https://apidock.com/rails/ActionView/RoutingUrlFor/url_for

    使用命名的路由助手会更容易,例如 images_path(image)images_url(image, host: 'your host') .

    如果你真的想使用 url_for 提供控制器和动作的路径选项: url_for(controller: 'images', action: 'show', id: image.id, host: 'your host')

  • 0

    经过研究,我发现的唯一解决方案是使用带有@DiegoSalazar建议的选项哈希的 url_for ,然后使用activeresource提供的 blobs 控制器和正确的参数,ej:

    Rails.application.routes.url_for(controller: 'active_storage/blobs', action: :show, signed_id: image.signed_id, filename: image.filename, host: 'www.example.com')

    说实话,我认为在模型范围内访问图像的永久URL应该是一种更简单的方法,但是现在是我找到的唯一解决方案 .

相关问题