我有一个订单表,它有一个item_details键,我想让item_details的值是一个对象数组?我该怎么做?这是我目前所拥有的。请求被成功发布,但它看起来像这样?我该怎么修复它?
订单管理员
class OrdersController < ApplicationController
skip_before_action :authorized, only: :create
def index
orders = Order.all
if orders
render json: orders
else
render json: {error: "Order Not Found" }, status: :not_found
end
end
def show
order = Order.find_by(id: params[:id])
if order
render json: order
else
render json: { error: "Order Not Found" }, status: :not_found
end
end
def create
order = Order.create(order_params)
render json: order, status: :created
end
def update
order = Order.find_by(id: params[:id])
if order
order.update(order_params)
render json: order
else
render json: { error: "Order Not Found" }, status: :not_found
end
end
private
def order_params
params.permit(:customer_id, :order_date,{ item_details: [:product_id, :quantity] })
end
end
订单序列化程序
class OrderSerializer < ActiveModel::Serializer
attributes :id, :customer_id, :order_date, :total_cost, :item_details
belongs_to :customer
has_many :order_details
has_many :products
def total_cost
cost = []
self.object.order_details.each do |details|
product = self.object.products.find {|product| product.id == details.product_id}
cost << product.price * details.quantity
end
return cost.sum
end
end
图式
create_table "orders", force: :cascade do |t|
t.integer "customer_id"
t.string "order_date"
t.datetime "created_at", precision: 6, null: false
t.datetime "updated_at", precision: 6, null: false
t.text "item_details", default: [], array: true
end
发布人员请求
{
"customer_id": 1,
"order_date": 1,
"item_details": [
{
"product_id": 1,
"quantity" : 2
},
{
"product_id": 7,
"quantity" : 1
}
]
}
Postman 返回
{
"id": 2,
"customer_id": 1,
"order_date": "1",
"total_cost": 0,
"item_details": [
"{\"product_id\"=>1, \"quantity\"=>2}",
"{\"product_id\"=>7, \"quantity\"=>1}"
],
"customer": {
"id": 1,
"name": "John Smith",
"phone_number": "(811) 833 2172",
"email": "john@yahoo.com",
"address": "334 Jacobs Plaza, West Robtport, IN 26209-0933",
"username": "john103",
"password": null
},
"order_details": [],
"products": []
}
我不知道为什么has看起来像这样“{“product_id”=〉1,“quantity”=〉2}”它是一个字符串而不是一个实际的对象?
1条答案
按热度按时间ttygqcqt1#
这是因为
item_details
数组没有被强制为JSON,而是被强制为字符串。看起来您正在传入一个
item_details
数组,但将其存储为字符串:因此,您可能希望存储一个散列数组。