如何获取Active Storage映像的URL

我想通过api获取带有附加图像的记录列表作为链接或文件。

我有一个简单的模型:

class Category < ApplicationRecord has_one_attached :image validates :name, presence: true, uniqueness: true end 

接下来的行动:

  def index @categories = Category.all.with_attached_image render json: @categories.to_json(include: { image_attachment: { include: :blob } }) end 

这是我获得图像对象的唯一方法。

我看到下一个结果:

 {"id":4,"name":"Cat1","description":""}, {"id":1,"name":"Cat2","description":"","image_attachment": {"id":8,"name":"image","record_type":"Category","record_id":1,"blob_id":8,"created_at":"2018-06-09T13:45:40.512Z","blob": {"id":8,"key":"3upLhH4vGxZEhhf3TaAjDiCW","filename":"Screen Shot 2018-06-09 at 20.43.24.png","content_type":"image/png","metadata": {"identified":true,"width":424,"height":361,"analyzed":true},"byte_size":337347,"checksum":"Y58zbYUVOlZRadx81wxOJA==","created_at":"2018-06-09T13:45:40.482Z"}}}, ... 

我可以在这里看到文件名。 但是文件存在于不同的文件夹中,对我而言,它似乎不是一种获取和链接到文件的便捷方式。

我找不到任何关于此的信息。

更新

根据iGian解决方案,我的代码变为:

  def index @categories = Category.all.with_attached_image render json: @categories.map { |category| category.as_json.merge({ image: url_for(category.image) }) } end 

对于我的User has_one_attached :avatar我可以使用<%= image_tag url_for(user.avatar) %>获取我的视图中的url。 所以,在控制器中我会使用url_for(user.avatar)

对于has_one_attached :image Category has_one_attached :image

 url_for(category.image) 

请按照此方式获取图像(如果您使用的是has_many_attached

 Model.images.map{|img| ({ image: url_for(img) })}