【问题标题】:How to serialize a has_many_attached in Active Model Serializer using JSON API format?如何使用 JSON API 格式在 Active Model Serializer 中序列化 has_many_attached?
【发布时间】:2021-08-18 12:27:46
【问题描述】:

截至目前,我有一个带有has_one_attached :file 的模型,我正在使用如下方法对其进行序列化。

# app/models/my_model.rb
class MyModel < ApplicationRecord
  has_one_attached :file

  def file_url
    if file.attached?
      Rails.application.routes.url_helpers.rails_blob_url(file)
    end
  end
end

然后在我的带有 activemodel 序列化器(JSON API 格式)的序列化器中

type :my_model

attributes(
  :file_url
)

这很好用,现在我要转移到 has_many_attached :files,我在序列化它时遇到了问题。我试过了:

class MyModel < ApplicationRecord
  has_many_attached :files
  
  def files_url
    files.each_With_object([]) do |file, array|
    array << Rails.application.routes.url_helpers.rails_blob_url(file)
  end
end

然后在我的 app/controller/my_model_controller.rb 中

  def my_model_params
    params.require(:my_model).permit(:files => [])
  end

最后,在我的序列化程序中,我只调用 :files_url(而不是像以前那样处理一个文件的 file_url),但它不起作用:

type :my_model

attributes(
  :files_url
)

知道我错过了什么吗?我似乎找不到很多关于序列化 has_many_attached 的有用信息。谢谢

【问题讨论】:

    标签: ruby-on-rails ruby active-model-serializers


    【解决方案1】:

    修好了!它确实有效,我只是向 Insomnia 发送了错误的参数。

    我将 my_model_params 中的 :files =&gt; [] 替换为 files: []。在 Insomnia 中,我将每个文件发送到 my_model[files][] 参数中。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-09-03
      • 1970-01-01
      • 2016-01-28
      • 1970-01-01
      • 2014-03-26
      • 1970-01-01
      • 1970-01-01
      • 2019-02-07
      相关资源
      最近更新 更多