Search code examples
rubyruby-on-rails-5

Rails API how to send attached images with the Product as response


I am trying to send a response back to a frontend client.

This is the response I am trying to create:

{
    "data": [
        {
            "id": 1,
            "product_title": "Some item"
            "images": ["imageurl1", "imageurl2", "imageurl3"]
            // other product info
        },
        {
            "id": 2,
            "product_title": "Some item"
            "images": ["imageurl4", "imageurl5", "imageurl6"]
            // other product info
        }
    ]
}

Currently it just looks like:

{
    "data": [
        {
            "id": 1,
            "product_title": "Some item"
            // other product info
        },
        {
            "id": 2,
            "product_title": "Some item"
            // other product info
        }
    ]
}

My product.rb looks like:

class Product < ApplicationRecord
  has_many_attached :images
end

Is there a way I can include the attached images in the Product object?

I have been messing around myself and I have tried looking on other posts but I have not found a solution that works.


Solution

  • You can use ActiveStorage's helpers for linking to files, as described in the Active Storage Overview Rails Guide.

    Example:

    url_for(user.avatar)
    

    Example for a download link with the content disposition set:

    rails_blob_path(user.avatar, disposition: "attachment")
    

    If you are generating your API output from a serializer class or something else besides the controller action, note the section on using the URL helpers from outside of the controller/view context:

    Rails.application.routes.url_helpers.rails_blob_path(user.avatar, only_path: true)
    

    These examples use user.avatar but in your example that would be an instance of one of the many images on your Product model.

    It's worth reading the entirety of that guide before deciding how to expose URLs in an API. For example, consider whether you need private/signed/authenticated URLs because by default these methods generate public URLs.