How can I get url of my attachment stored in active storage in my rails controller

Mobeen picture Mobeen · May 19, 2018 · Viewed 13.3k times · Source

How can I get url of my has_one model attachment stored in active storage in my rails controller. So, that I would be able to send it as full link as api in json. So far, I have tried following methods but each of them are giving various issues:

  1. current_user.image.service_url ---- undefined method `service_url' for #<ActiveStorage::Attached::One:0x....

  2. Rails.application.routes.url_helpers.rails_disk_blob_path(current_user.image, only_path: true), it gives me an output like:

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

but this is not a url, right? I am not able to hit and get image on browser.

  1. url_for ----

    undefined method `active_storage_attachment_url' for #<Api::V1::UsersController:0x007f991c1eaa98

Answer

Jonatas  Eduardo picture Jonatas Eduardo · Jan 8, 2019

Use the method rails_blob_path for attachements in a controller and models

For example, if you need to assign a variable (e.g. cover_url) in a controller, first you should include url_helpers and after use method rails_blob_path with some parameters. You can do the same in any model, worker etc.

Complete example below:

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