Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 216
Nenad Novković Avatar asked Nov 20 '25 15:11

Nenad Novković


1 Answers

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
like image 66
Nenad Novković Avatar answered Nov 22 '25 03:11

Nenad Novković