Deepak Chauhan
Deepak Chauhan

Reputation: 13

Render image URL from Active Storage through jBuilder

I have a product model. It has relationship has_one_attached :image with ActiveStorage. Now, my objective is to send product data along with the image URL as that URL, I will be using in my image tag to display the image. The image is stored locally on Disk.

My model

class Product < ApplicationRecord
  has_one_attached :image
end

My Controller

class ProductsController < ApplicationController
  def index
    @products = Product.all
  end
end

json builder

json.products @products do |product|
  json.id product.id
  json.name product.name
  json.price product.price
  if product.image.attached?
    json.image_url url_for(product.image)
  end
end

For image URL I am getting this URL "rails/active_storage/blobs/redirect/eyJfcmFpbHMiOnsibWVzc2FnZSI6IkJBaEpJaWt3TkdZeFpEWTRaUzAzTkdWakxUUTNNRE10WWpjeU9TMDJaakpqTm1ObVpEQmlNV0VHT2daRlZBPT0iLCJleHAiOm51bGwsInB1ciI6ImJsb2JfaWQifX0=--8eb2ebae829b10c1c57bb13a035a122106c4ff6e/lays" which my image tag on react component is not able to read.

Upvotes: 1

Views: 2099

Answers (1)

Randomtheories
Randomtheories

Reputation: 1290

json.image_url rails_blob_url(product.image)

worked for me. However, you have to check if image is attached first.

Upvotes: 1

Related Questions