【问题标题】:Generate image URL in model - ActiveStorage在模型中生成图像 URL - ActiveStorage
【发布时间】:2018-09-07 15:11:41
【问题描述】:

我有一个使用 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 的正确方法是什么?

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-5 rails-activestorage


    【解决方案1】:

    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')

    【讨论】:

    • images_path 不是 activestorage 提供的,所以我认为不能使用
    • 对,你必须在Rails.application.routes.url_helpers 上调用它,就像你已经在做的那样。
    • 我的意思是 images_path 帮助器在 activestorage 中甚至不可用,即使使用 Rails.application.routes.url_helpers.images_path 也无法工作
    • 我假设你已经在 routes.rb 文件中声明了一个命名路由。将images_path 替换为您的相关命名路线,或者仅将url_for 与上述选项一起使用。
    • 我不认为在 routes.rb 中声明新路由应该是正确的,一定更容易为什么用 activestorage 处理这个问题,再次考虑使用 url_for 和哈希选项跨度>
    【解决方案2】:

    使用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
    

    【讨论】:

      【解决方案3】:

      经过调查,我发现唯一的解决方案是使用@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 应该是一种更简单的方法,但目前是我找到的唯一解决方案。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-06-05
        • 1970-01-01
        • 2018-08-28
        • 2020-04-24
        • 1970-01-01
        • 2020-02-21
        • 2017-07-15
        • 1970-01-01
        相关资源
        最近更新 更多