Skip to main content

Exposing API when uploading image with ActiveStorage in Rails 5.2

General • Asked by 6696

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


Login or Create An Account to join the conversation.

Subscribe to the newsletter

Join 27,623+ developers who get early access to new screencasts, articles, guides, updates, and more.

    By clicking this button, you agree to the GoRails Terms of Service and Privacy Policy.

    More of a social being? We're also on Twitter and YouTube.