Include ActiveStorage URL to image in JSON response?

Viewed 639

I'm trying to simply show the URL to images which I've attached to my User model.

  def show
    render json: @user, include: [:images]
  end

The above response gives me:-

{
    "id": 2288,
    "name": "Joe Bloggs",
    "images": [
        {
            "id": 1,
            "name": "images",
            "record_type": "User",
            "record_id": 2288,
            "blob_id": 1,
            "created_at": "2021-04-20T13:53:16.663Z"
        }
    ]
}

From the Rails API docs and other stackoverflow posts, I should be using the service_url or url method like below:-

  def show
    render json: @user, include: [images: {methods: :service_url}]
  end

The above however, gives me:-

"status": 500,
"error": "Internal Server Error",
"exception": "#<URI::InvalidURIError: bad URI(is not URI?): nil>",

How do I achieve what I want here?

I've also used binding.pry to try and manually get the path with

@user.images.first.url
@user.images.first.blob
@user.images.first.blob.url
@user.images.first.blob.service_url

and every single one of the above gives me:-

NameError: uninitialized constant #<Class:0x0000ffffb02e5e18>::Analyzable

A bit stumped as to why this isn't easily done in Rails.

1 Answers

The solution to this was to set the host, by adding the below:-

include ActiveStorage::SetCurrent

in my controller.

Related