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

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

Sometimes, e.g. an API needs to return the full url with host / protocol for the clients (e.g. mobile phones etc.). In this case, passing the host parameter to all of the rails_blob_url calls is repetitive and not DRY. Even, you might need different settings in dev/test/prod to make it work.

If you are using ActionMailer and have already configuring that host/protocol in the environments/*.rb you can reuse the setting with rails_blob_url or rails_representation_url.

# in your config/environments/*.rb you might be already configuring ActionMailer
config.action_mailer.default_url_options = { host: 'www.my-site.com', protocol: 'https' }

I would recommend just calling the full Rails.application.url_helpers.rails_blob_url instead of dumping at least 50 methods into your model class (depending on your routes.rb), when you only need 2.

class MyModel < ApplicationModel
  has_one_attached :logo

  # linking to a variant full url
  def logo_medium_variant_url
    variant = logo.variant(resize: "1600x200>")   
    Rails.application.routes.url_helpers.rails_representation_url(
      variant, 
      Rails.application.config.action_mailer.default_url_options
    )
   end

  # linking to a original blob full url
  def logo_blob_url
    Rails.application.routes.url_helpers.rails_blob_url(
      logo.blob, 
      Rails.application.config.action_mailer.default_url_options
    )
  end
end