Rails API导入JSON文件入库时所有字段存为nil如何解决?
问题根因
一共有4个核心错误导致字段全为nil:
- 你上传的JSON文件解析后是数组结构,包含多个产品属性,直接把数组传给
Product.new方法(该方法仅接收单个对象的属性哈希),根本无法正确匹配属性 - JSON中的
type字段和数据库实际存储的product_type字段名不匹配,即使你传单个哈希也无法给对应字段赋值 - 如果你是通过表单上传文件,
params[:products]是Rails封装的ActionDispatch::Http::UploadedFile对象,直接传给File.open无法正确读取文件内容 - 未处理Rails强参数校验,未许可的属性会被自动过滤
修复方案
方案1:批量导入所有产品(符合JSON数据结构的常规需求)
def create # 正确读取上传的JSON文件内容 file = params[:products] content = JSON.parse(file.read) # 修正键名映射,适配数据库字段 product_attrs = content.map do |item| item.transform_keys { |k| k == 'type' ? 'product_type' : k } end # 批量创建产品 @products = Product.create!(product_attrs) render json: { message: '产品保存成功', data: @products }, status: :ok rescue JSON::ParserError render json: { error: 'JSON文件格式错误' }, status: :bad_request rescue ActiveRecord::RecordInvalid => e render json: { error: e.record.errors.full_messages }, status: :unprocessable_entity end
方案2:仅导入第一个产品(适配原代码单条保存逻辑)
def create file = params[:products] # 取数组第一个元素作为单条产品属性 content = JSON.parse(file.read).first attrs = content.transform_keys { |k| k == 'type' ? 'product_type' : k } @product = Product.new(attrs) if @product.save render json: { message: '产品保存成功', data: @product }, status: :ok else render json: @product.errors, status: :unprocessable_entity end rescue JSON::ParserError render json: { error: 'JSON文件格式错误' }, status: :bad_request end
额外配置要求
如果你的Rails版本开启了属性批量赋值保护,需要在Product模型中显式声明可批量赋值的字段:
class Product < ApplicationRecord permits :title, :product_type, :description, :filename, :height, :width, :price, :rating end
内容的提问来源于stack exchange,提问作者Daniel_Rocha
相关产品推荐
相关产品推荐

