4

我有一个使用 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.application.routes.url_helpers.url_for(image)按照 rails 指南(http://edgeguides.rubyonrails.org/active_storage_overview.html#linking-to-files)中的建议,但它会引发这个错误:

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 的正确方法是什么?

4

3 回答 3

10

rails_blob_path在模型和控制器中使用附件的方法

例如,如果您需要cover_url在模型中创建一个方法(例如 ),首先您应该url_helpers在使用方法之后rails_blob_path包含一些参数。您可以在任何控制器、工作人员等中执行相同的操作。

完整示例如下:

class Event < ApplicationRecord

  include Rails.application.routes.url_helpers

  def cover_url 
    rails_blob_path(self.cover, disposition: "attachment", only_path: true)
  end

end
于 2019-01-08T07:34:26.650 回答
0

在调查我发现的唯一解决方案是使用url_for@DiegoSalazar 建议的选项哈希后,然后使用blobs由activeresource 提供的控制器和正确的参数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 的一种更简单的方法,但目前是我找到的唯一解决方案。

于 2018-03-29T17:09:09.337 回答
-2

url_for通常采用选项的哈希值,如果您传入模型,您将无法提供host选项:https ://apidock.com/rails/ActionView/RoutingUrlFor/url_for

例如,使用命名路由助手会更容易。image_path(image)image_url(image, host: 'your host')

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

于 2018-03-29T16:39:56.193 回答