【问题标题】:Include ActiveStorage URL to image in JSON response?在 JSON 响应中包含 ActiveStorage URL 到图像?
【发布时间】:2021-04-21 12:15:18
【问题描述】:

我试图简单地显示我附加到我的用户模型的图像的 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 文档和其他 stackoverflow 帖子中,我应该使用 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 中不容易做到。

【问题讨论】:

标签: ruby-on-rails ruby rails-activestorage


【解决方案1】:

解决方案是通过添加以下内容来设置主机:-

include ActiveStorage::SetCurrent

在我的控制器中。

【讨论】:

    猜你喜欢
    • 2014-10-07
    • 2018-09-07
    • 1970-01-01
    • 2013-10-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-09-01
    相关资源
    最近更新 更多