ruby-on-rails - 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
这个 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
解决方案
更改 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
我从这里得到了答案
推荐阅读
- html - 如何避免过渡和变换结合时对“悬停”的“抖动效应”?
- python - 如何将数据框列对转换为单个字典映射?
- html - 将 div 固定到页面中心,但调整大小时不会溢出
- node.js - Node.js 使用 AWS EC2 IAM 角色凭证获取签名 URL
- python - 新的 Python 3.1 不能识别简单变量?
- wordpress - 如何将选择数据放入 Whatsapp 按钮?
- javascript - 在 Chrome 控制台中显示 HTML 多行“style=-lns ...”
- android - android studio在用户不活动时停止可运行处理程序
- libstdc++ - 如何在 libstdc++.so.6 中升级 CXXABI 的版本
- c# - C# 回文测试