在 JSON 响应中包含 ActiveStorage URL 到图像?

Include ActiveStorage URL to image in JSON response?

我试图简单地向我附加到我的用户模型的图像显示 URL。

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

以上回复给我:-

{
    "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"
        }
    ]
}

从 Rails API 文档和其他 Whosebug 帖子,我应该使用 service_urlurl 方法,如下所示:-

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

然而,上面的内容给了我:-

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

如何在这里实现我想要的?

我还使用 binding.pry 尝试手动获取路径

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

上面的每一个都给我:-

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

对于为什么在 Rails 中不容易做到这一点有点困惑。

解决这个问题的方法是通过添加以下内容来设置主机:-

include ActiveStorage::SetCurrent

在我的控制器中。