【发布时间】: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