Home > Net >  Include ActiveStorage attachments in JSON response in rails?
Include ActiveStorage attachments in JSON response in rails?

Time:02-18

This url provides information for all 'products':

require 'open-uri'
JSON.load(open("http://localhost:3000/products.json"))

But I added ActiveStorage attachments; now each product has one 'main_image' and zero or more 'secondary_images'.

I'd like to update the API response to provide the URLs to all attachments (example code to generate the url: app.url_for(Product.find(10).main_image)) as part of the JSON response (just like it currently does for all other product attributes).

Does rails have a built-in quick/easy way to make the API response provide associated ActiveStorage info?

Additional notes:

Currently, app/views/products/_product.json.jbuilder` looks like this:

json.extract! product, :id, :price, :created_at, :updated_at
json.url product_url(product, format: :json)

CodePudding user response:

I had to do a similar thing and I solved it by grabbing the records, and then adding the data. This was the quickest, easiest way I could find to achieve it.

@products = Product.find(10)
@products = @products.map {|prod| prod.as_json.merge({ main_image: prod.main_image.service_url })}

That will then output the records as json with the URL for the image in there.

I think I may have that correct for your values but it could be off.

  • Related