Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get url of Active Storage image

Tags:

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 
like image 700
zishe Avatar asked Jun 09 '18 15:06

zishe


People also ask

How do I find the active storage image URL?

Also try @object. image. service_url . This will give you the url where the image is saved.

Where are active storage files stored?

By default in the development environment, Active Storage stores all uploaded images on your local disk in the storage subdirectory of the Rails application directory. That's the file you uploaded!

What is Activestorage?

Active Storage facilitates uploading files to a cloud storage service like Amazon S3, Google Cloud Storage, or Microsoft Azure Storage and attaching those files to Active Record objects.

What is active storage blob?

A blob is a record that contains the metadata about a file and a key for where that file resides on the service. Blobs can be created in two ways: Subsequent to the file being uploaded server-side to the service via create_after_upload!.


2 Answers

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) 
like image 164
iGian Avatar answered Sep 23 '22 13:09

iGian


Also try @object.image.service_url. This will give you the url where the image is saved. I.E. url to amazon s3 storage.

like image 30
AnthonyM. Avatar answered Sep 23 '22 13:09

AnthonyM.