API, сохраняющий несколько дочерних записей, сохраняет только одну с отсутствующими полями ruby - PullRequest
0 голосов
/ 22 июня 2019

Выполнение вызова 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

вот изображение командной строки enter image description here

как вы видите здесь, предмет был сохранен enter image description here

как вы видите здесь, он взял только одно изображение с 3 полями enter image description here

this 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

Ответы [ 2 ]

0 голосов
/ 22 июня 2019

изменение 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

0 голосов
/ 22 июня 2019

Сначала ваш 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"}
]}

и второе обновление

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

с

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])

конец

и создайте метод с помощью

def create
 @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
...