21

I can get url in model with this code (Active Storage)

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

But I need to get url of a resized variant

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

For example this code

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

throw

NoMethodError (undefined method `signed_id' for #< ActiveStorage::Variant:0x0000000004ea6498 >):
Felix
  • 4,510
  • 2
  • 31
  • 46
ViT-Vetal-
  • 2,431
  • 3
  • 19
  • 35

4 Answers4

53

Solution:

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

Answer provided 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.

ViT-Vetal-
  • 2,431
  • 3
  • 19
  • 35
  • 3
    You can remove the `.processed` in order to have this lazily executed when the image is first fetched. You can also remove `only_path: true` and just call `rails_representation_path` instead of `rails_representation_url`. – Brendon Muir Jun 08 '21 at 21:01
0
variant = picture_of_car
            .variant(resize: '300x300')
            .processed 

variant.service.send(:path_for, variant.key) # Absolute path to variant file
hazg
  • 318
  • 2
  • 10
0

Following the documentation at https://api.rubyonrails.org/classes/ActiveStorage/Variant.html it should be: picture_of_car.variant(resize: [300, 300]).processed.service_url

Salz
  • 152
  • 1
  • 8
  • you are not right - in section related to `service_url` it is written that you shouldn't use it directly, instead use `url_for(variant)` – kaleb4eg Jul 11 '20 at 12:51
0

Just adding on here, if you're just needing a url for an Active Storage attachment to pass to an HTML element that Rails doesn't have a native *_tag method for, you can use url_for in scope and it'll work. In my case it was a <picture> tag. For an image it's easy:

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

For a <picture> tag (no native picture_tag helper) it's almost as easy:

<picture>
  <source srcset="<%= url_for(@thing.foo_image.variant :large) %>">
Jon Sullivan
  • 193
  • 2
  • 6