Reputation: 2471
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 >):
Upvotes: 22
Views: 14145
Reputation: 333
👋🏻 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) %>">
Upvotes: 0
Reputation: 152
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
Upvotes: 0
Reputation: 358
variant = picture_of_car
.variant(resize: '300x300')
.processed
variant.service.send(:path_for, variant.key) # Absolute path to variant file
Upvotes: 0
Reputation: 2471
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.
Upvotes: 56