如何在Active Model Serializer中按JSON API格式序列化has_many_attached字段
问题修复方案
1. 修复模型方法的语法错误
你写的files_url方法存在2处语法问题:
- 迭代方法名拼写错误:
each_With_object的W必须小写,正确写法是each_with_object - 迭代块缺少闭合的
end,导致方法结构异常
修正后的模型代码如下:
# app/models/my_model.rb class MyModel < ApplicationRecord has_many_attached :files def files_url return [] unless files.attached? files.each_with_object([]) do |file, array| array << Rails.application.routes.url_helpers.rails_blob_url( file, host: Rails.application.config.active_storage.default_url_options[:host] ) end end end
2. 补全Active Storage默认URL配置
Rails生成存储文件URL时需要指定服务域名,你需要在对应环境的配置文件中添加默认配置:
# config/environments/development.rb 开发环境配置 config.active_storage.default_url_options = { host: 'localhost', port: 3000 } # config/environments/production.rb 生产环境配置替换为你的正式域名 # config.active_storage.default_url_options = { host: 'your-domain.com' }
3. 避免N+1查询问题
查询MyModel数据时预加载附件资源,提升接口性能:
# 控制器查询代码示例 @my_model = MyModel.with_attached_files.find(params[:id]) @my_models = MyModel.with_attached_files.all
4. 现有配置校验
你已经完成的参数白名单配置、序列化器配置都是正确的,不需要额外修改。如果修复后仍有问题,可以先在Rails控制台调用实例的files_url方法,确认方法返回正常的URL数组后再排查序列化器逻辑。
内容的提问来源于stack exchange,提问作者GuidoMedina
相关产品推荐
相关产品推荐

