代码之家  ›  专栏  ›  技术社区  ›  zishe

如何获取活动存储映像的URL

  •  9
  • zishe  · 技术社区  · 6 年前

    我想通过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
    
    2 回复  |  直到 6 年前
        1
  •  16
  •   iGian    6 年前

    User has_one_attached :avatar <%= image_tag url_for(user.avatar) %> url_for(user.avatar)

    Category has_one_attached :image

    url_for(category.image)
    
        2
  •  2
  •   Luca Kiebel    6 年前

    Model.images.map{|img| ({ image: url_for(img) })}
    
    推荐文章