15

如何获取存储在我的 rails 控制器的活动存储中的 has_one 模型附件的 url。因此,我将能够将其作为 json 中的 api 的完整链接发送。到目前为止,我已经尝试了以下方法,但它们中的每一个都给出了各种问题:

  1. current_user.image.service_url---- #<ActiveStorage::Attached::One:0x 的未定义方法 `service_url'....

  2. Rails.application.routes.url_helpers.rails_disk_blob_path(current_user.image, only_path: true),它给了我这样的输出:

    "/rails/blob/%23%3CActiveStorage::Attached::One:0x007f991c7b41b8%3E"

但这不是一个网址,对吧?我无法在浏览器上点击并获取图像。

  1. url_for ----

    #<Api::V1::UsersController:0x007f991c1eaa98 的未定义方法“active_storage_attachment_url”

4

4 回答 4

13

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

例如,如果您需要cover_url在控制器中分配一个变量(例如 ),首先您应该url_helpers在使用方法后rails_blob_path包含一些参数。你可以在任何模型、工人等中做同样的事情。

完整示例如下:

class ApplicationController < ActionController::Base

  include Rails.application.routes.url_helpers

  def index
    @event = Event.first
    cover_url = rails_blob_path(@event.cover, disposition: "attachment", only_path: true)
  end

end
于 2019-01-08T07:29:36.023 回答
9

有时,例如 API 需要为客户端(例如手机等)返回带有主机/协议的完整 url。在这种情况下,将主机参数传递给所有 rails_blob_url 调用是重复的,而不是 DRY。甚至,您可能需要在 dev/test/prod 中进行不同的设置才能使其正常工作。

如果您正在使用 ActionMailer 并且已经在 environment/*.rb 中配置了该主机/协议,则可以使用rails_blob_urlor重用该设置rails_representation_url

# in your config/environments/*.rb you might be already configuring ActionMailer
config.action_mailer.default_url_options = { host: 'www.my-site.com', protocol: 'https' }

当您只需要 2 个时,我建议您只调用完整Rails.application.url_helpers.rails_blob_url的方法,而不是将至少 50 个方法转储到您的模型类中(取决于您的 routes.rb)。

class MyModel < ApplicationModel
  has_one_attached :logo

  # linking to a variant full url
  def logo_medium_variant_url
    variant = logo.variant(resize: "1600x200>")   
    Rails.application.routes.url_helpers.rails_representation_url(
      variant, 
      Rails.application.config.action_mailer.default_url_options
    )
   end

  # linking to a original blob full url
  def logo_blob_url
    Rails.application.routes.url_helpers.rails_blob_url(
      logo.blob, 
      Rails.application.config.action_mailer.default_url_options
    )
  end
end

于 2019-03-13T10:37:39.687 回答
0

我没有使用过 Rails 主动存储,但我在文档中读到的内容可能会对您有所帮助

尝试rails_blob_url(model.image)

更多http://edgeguides.rubyonrails.org/active_storage_overview.html

于 2018-05-19T12:26:26.910 回答
-1

我能够使用以下命令在浏览器中查看图像:

<%= link_to image_tag(upload.variant(resize: "100x100")), upload %>

upload附图在哪里。

于 2018-05-21T11:08:09.920 回答