首页 > 解决方案 > api保存多个子记录只保存一个缺少字段ruby

问题描述

进行具有父记录(即项目)和子记录(即照片)的 api 调用,项目记录可以很好地保存,但图像只保存一个缺少字段的图像。

这是我发送的json

{"item_category": "Books & Magazines", "item_condition": "Used",
"item_name": "Crushing it", "summary": "super awesome",
"price": 20, "active": true,"instant": 1,
"access_token": "p8Z-yZ1wRooBLsZj4yeS",
"photo_attributes":
[{"created_at": "2019-05-16 05:28:16.696408",
"image_file_name": "images.jpg",
"image_content_type": "image/jpeg","image_file_size": 257908,
"image_updated_at":"2019-05-21 15:20:55.390445"},
{"created_at": "2019-05-16 05:28:16.696408",
"image_file_name": "images.jpg",
"image_content_type": "image/jpeg","image_file_size": 257908,
"image_updated_at":"2019-05-21 15:20:55.390445"}
]}

这是我调用的 api

http://localhost:3000/api/v1/createitem

这是命令行的图像 在此处输入图像描述

如您在此处看到的,该项目已保存 在此处输入图像描述

正如您在此处看到的,它只拍摄了一张包含 3 个字段的图像 在此处输入图像描述

这个 items.contoller.rb

 class Api::V1::ItemsController < ApplicationController
 def createitem
   @item = current_user.items.new(item_params)
   if @item.save 
     render json: @item, status: :ok
   else
     render json: { error: "Something went wrong", is_success: false}, status: 422
   end
 end
 def item_params
       params.require(:item).permit(:item_category, :item_condition,:item_name,:summary,:address,:price,:active, :instant, photo_attributes:[:created_at, :image_file_size, :image_updated_at, :image_file_name, :image_content_type])
  end
 end

这是 item.rb 模型

class Item < ApplicationRecord
enum instant: {Request: 0, Instant: 1}

belongs_to :user
has_many :photos
accepts_nested_attributes_for :photos

validates :item_category, presence: true
validates :item_condition, presence: true
end

我厌倦了这个解决方案,但仍然没有保存任何照片 Rails 4 嵌套属性没有保存

这是更新 items.controller.rb

class Api::V1::ItemsController < ApplicationController
 def createitem
   @item = current_user.items.build(item_params)
   @item.photos.each do |photo|
     photo.build
   end
   if @item.save 
     render json: @item, status: :ok
   else
     render json: { error: "Something went wrong", is_success: false}, status: 422
   end
 end
 def item_params
   params.require(:item).permit(:item_category, :item_condition,:item_name,:summary,:address,:price,:active, :instant, photos_attributes:[:created_at, :image_file_size, :image_updated_at, :image_file_name, :image_content_type])
  end
 end

标签: ruby-on-railsrubyrails-api

解决方案


更改 item_parms def 修复了问题

def item_params
 params[:item][:photos_attributes] = params[:photos_attributes]
 params.require(:item).permit(:item_category, :item_condition,:item_name,:summary,:address,:price,:active, :instant, photos_attributes:[:image_file_size, :image_updated_at, :image_file_name, :image_content_type])
end  

我从这里得到了答案

Rails 5.1 API - 如何允许嵌套 JSON 对象属性的参数


推荐阅读