I want to get list of records with attached images as a links or files by api.
I have a simple model:
class Category < ApplicationRecord
has_one_attached :image
validates :name, presence: true, uniqueness: true
end
And next action:
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.
Updated
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
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)
For Category
which has_one_attached :image
:
url_for(category.image)