Rails 5.2 API ActiveStorage 如何获取URL 多图路径?

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

我正在从回形针迁移到 Rails 5.2 和活动存储。我仅将 rails 用作 API。

如何获取 URL has_many_attached 的路径 :images

这是适用于单个文件的代码:

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

当我尝试为多图像做类似的事情时,我只是得到那些图像,而不是它们的 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

解决方法如下:

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