I have a rake task which stores images in ActiveStorage
. In the same rake task I need the attachment URL of those images.
In a normal Rails context, I'd use url_for(my_attachment)
. That helper is not available in a rake task though.
I tried to include the route helper:
task my_task: :environment do
include MyApp::Application.routes.url_helpers
attachment = my_model.image.attach(..)
url_for(attachment)
end
Which results in:
*** NoMethodError Exception: undefined method `attachment_url' for main:Object
Is there any way to get the public URL of an attachment in a rake task?
I wasted a lot of time looking for get a file URL working on a Module file, but here is the answer:
If you need to create a link from outside of controller/view context (Background jobs, Cronjobs, etc.), you can access the rails_blob_path like this:
Rails.application.routes.url_helpers.rails_blob_path(user.avatar, only_path: true)
I founded this on this link Redirect Mode :: Active Storage