All threads / Exposing API when uploading image with ActiveStorage in Rails 5.2

Ask A Question

Notifications

You’re not receiving notifications from this thread.

Exposing API when uploading image with ActiveStorage in Rails 5.2

Lauro asked in General

I'm trying to expose my API, but I'm having a hard time exposing an image that I uploaded using ActiveStorage. This is the current out put from the console when running Recipe.last.image:

 => #<ActiveStorage::Attached::One:0x00007fd502f47660 @name="image", @record=#<Recipe id: 10, user_id: 2, title: "Gin & Tonic", preparation: "New Recipe\r\nTitle\r\n\r\nGin & Tonic\r\nIngredients\r\n\r\nP...", ingredients: "New Recipe\r\nTitle\r\n\r\nGin & Tonic\r\nIngredients\r\n\r\nP...", created_at: "2018-07-24 18:54:49", updated_at: "2018-07-24 18:54:49">, @dependent=:purge_later>

How can I expose the actuall image URL when using ActiveStorage?

When exposing an image from ActiveStorage you first need to access :active_storage_blobs to expose:

      t.string   :key,        null: false
      t.string   :filename,   null: false
      t.string   :content_type
      t.text     :metadata
      t.bigint   :byte_size,  null: false
      t.string   :checksum,   null: false
      t.datetime :created_at, null: false

Then you can go into your API and expose the Json data the following way:
json.images @recipe.image.key

Join the discussion

Want to stay up-to-date with Ruby on Rails?

Join 37,344+ developers who get early access to new tutorials, screencasts, articles, and more.

    We care about the protection of your data. Read our Privacy Policy.

    logo Created with Sketch.

    Ruby on Rails tutorials, guides, and screencasts for web developers learning Ruby, Rails, Javascript, Turbolinks, Stimulus.js, Vue.js, and more. Icons by Icons8

    © 2020 GoRails, LLC. All rights reserved.