如何在模型中获得 url 个图像变体(在 controller/view 之外)?主动存储

How can I get url of image variant in model (outside of controller/view)? Active Storage

我可以使用此代码(Active Storage)在模型中获得 url

Rails.application.routes.url_helpers.rails_blob_path(picture_of_car, only_path: true)

但我需要 url 调整大小的 varian

picture_of_car.variant(resize: "300x300").processed

例如这段代码

Rails.application.routes.url_helpers.rails_blob_path(picture_of_car.variant(resize: "300x300").processed, only_path: true)

投掷

NoMethodError (undefined method `signed_id' for #< ActiveStorage::Variant:0x0000000004ea6498 >):

解决方案:

Rails.application.routes.url_helpers.rails_representation_url(picture_of_car.variant(resize: "300x300").processed, only_path: true)

已提供答案 here

for a variant you need to use rails_representation_url(variant) - this will build a url similar to the one that rails_blob_url builds but specifically for that variant.

variant = picture_of_car
            .variant(resize: '300x300')
            .processed 

variant.service.send(:path_for, variant.key) # Absolute path to variant file

根据 https://api.rubyonrails.org/classes/ActiveStorage/Variant.html 处的文档,它应该是: picture_of_car.variant(resize: [300, 300]).processed.service_url

如果您只需要 url 将 Active Storage 附件传递给 HTML 元素,而 Rails 没有本机 *_tag 方法,您可以在范围内使用 url_for 并且它会起作用。在我的例子中,它是一个 <picture> 标签。对于图像很简单:

<%= image_tag @thing.foo_image.variant(:medium), class: "mx-auto" %>

对于 <picture> 标签(没有原生 picture_tag 帮助器)几乎一样简单:

<picture>
  <source srcset="<%= url_for(@thing.foo_image.variant :large) %>">