Search code examples
ruby-on-railsrails-activestorageruby-on-rails-5.2

Rails 5.2 API ActiveStorage how to get URL paths for multi image?


I am migrating from paperclip to Rails 5.2 and active storage. I am using rails as API-only.

How to get URL paths for has_many_attached :images

This is the code for the single file that works:

class UserSerializer < ActiveModel::Serializer
include Rails.application.routes.url_helpers
attributes %i[email name username]
....
  attribute :verification_url do
    if object.verification_file.attachment
      URI.join(ActionController::Base.asset_host, rails_blob_path(object.verification_file))
    end
  end
....

end

And when I try to do something similar for multi-images I am just getting those images, not their URL.

 include Rails.application.routes.url_helpers
 attributes :id, :name, :description, :images

 def images
  if object.images.attachments
    object.images.each do |image| 
      URI.join(ActionController::Base.asset_host, rails_blob_path(image))
    end
  end 
end

Solution

  • Here is the solution:

    def images
      return unless object.images.attachments
      image_urls = object.images.map do |image| 
        URI.join(
          ActionController::Base.asset_host, 
          rails_blob_path(image))
      end
    
      image_urls
    end