3

我正在从回形针迁移到 Rails 5.2 和活动存储。我只使用 Rails 作为 API。

如何获取has_many_attached 的 URL 路径: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
4

1 回答 1

5

这是解决方案:

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
于 2018-05-23T06:53:21.943 回答