1

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.

  • Where are you storing images, local or Amazon S3 or any other location? Check this config `config.active_storage.service` – Jagdish Feb 02 '22 at 17:07
  • I am storing image locally – Deepak Chauhan Feb 02 '22 at 17:12
  • Try this `json.image_url product.image.url` – Jagdish Feb 02 '22 at 17:17
  • Tried that earlier as well. This gives me "http://localhost:3000/rails/active_storage/disk/eyJfcmFpbHMiOnsibWVzc2FnZSI6IkJBaDdDVG9JYTJWNVNTSWhZVGx5YXpkM04yWmlaWGt3Wm01dWEyWnVhMjVyZG10bGFYVjFiUVk2QmtWVU9oQmthWE53YjNOcGRHbHZia2tpTjJGMGRHRmphRzFsYm5RN0lHWnBiR1Z1WVcxbFBTSnNZWGx6SWpzZ1ptbHNaVzVoYldVcVBWVlVSaTA0Snlkc1lYbHpCanNHVkRvUlkyOXVkR1Z1ZEY5MGVYQmxTU0lkWVhCd2JHbGpZWFJwYjI0dmIyTjBaWFF0YzNSeVpXRnRCanNHVkRvUmMyVnlkbWxqWlY5dVlXMWxPZ3BzYjJOaGJBPT0iLCJleHAiOiIyMDIyLTAyLTAyVDE3OjM5OjQ1LjAwNFoiLCJwdXIiOiJibG9iX2tleSJ9fQ==--a2919cc5f9a219cd0ebffe5834b33fdf85d9b115/lays" which doesn't work – Deepak Chauhan Feb 02 '22 at 17:36
  • This might be useful https://stackoverflow.com/questions/49791684/how-to-retrieve-attachment-url-with-rails-active-storage-with-s3 – Jagdish Feb 02 '22 at 18:18

1 Answers1

0
json.image_url rails_blob_url(product.image)

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

Randomtheories
  • 1,220
  • 18
  • 22