如何获取 Active Storage 图像的 url [英] How to get url of Active Storage image
问题描述
我想通过 api 获取带有附加图像的记录列表作为链接或文件.
I want to get list of records with attached images as a links or files by 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
这是我获取图像对象的唯一方法.
That's the only way I can get image object.
然后我看到下一个结果:
And I see next results:
{"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"}}},
...
我可以在这里看到文件名.但是文件位于不同的文件夹中,对我来说这似乎不是获取和链接到文件的便捷方式.
I can see filename here. But files lives in different folders and it doesn't seems for me like a convenient way to get and link to the file.
我找不到任何关于此的信息.
I couldn't find any information about this.
更新
根据 iGian 解决方案,我的代码变为:
Accordin to iGian solution my code become:
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
我可以使用 在我的视图中获取 url<%= image_tag url_for(user.avatar) %>
.所以,在控制器中我只会使用 url_for(user.avatar)
For my User
which has_one_attached :avatar
I can get the url in my views with <%= image_tag url_for(user.avatar) %>
.
So, in controller I would use just url_for(user.avatar)
对于 Category
其中 has_one_attached :image
:
url_for(category.image)
这篇关于如何获取 Active Storage 图像的 url的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!