从数据库 to_json 渲染数据效果很好
def getOrderDetails
#To get the details of a particular guest_order and its batches and items
@guest_order = GuestOrder.find(params[:id])
render json: @guest_order.to_json(except: [:created_at, :updated_at],
include: {order_batches: {except: [:guest_order_id, :created_at, :updated_at],
include: {order_items: {except: [:order_batch_id, :created_at, :updated_at] } }
}
}
)
end
但是,如何将相同表的数据保存到数据库中。参数是
Parameters: {"guestOrder"=>"{\"GuestOrder\"{\"GuestOrderId\":1,
\"orderTime\":\"2012-04-25 18:28:30\",\"notes\":\"spicy\",\"userId\":14,\"tableId\":1,
\"batch\":[{\"items\":[{\"itemId\":1,\"quantity\":4,\"dishId\":1},
{\"itemId\":2,\"quantity\":4,\"dishId\":3},
{\"itemId\":3,\"quantity\":3,\"dishId\":6}],
\"placed\":\"2012-04-25 18:28:30\",\"batchId\":1}],
\"numberOfAdults\":1,\"numberOfChilderns\":3}}"}
我已经像这样解析了参数值,
def guestOrder
guest_order = JSON.parse(params["guestOrder"])
# How to store the values from guest_order to database tables
end
1.9.2p290 :002 > guestOrder = JSON.parse("{\"GuestOrder\"{\"GuestOrderId\":1,
\"orderTime\":\"2012-04-25 18:28:30\",\"notes\":\"spicy\",\"userId\":14,\"tableId\":1,
\"batch\":[{\"items\":[{\"itemId\":1,\"quantity\":4,\"dishId\":1},
{\"itemId\":2,\"quantity\":4,\"dishId\":3},
{\"itemId\":3,\"quantity\":3,\"dishId\":6}],
\"placed\":\"2012-04-25 18:28:30\",\"batchId\":1}],
\"numberOfAdults\":1,\"numberOfChilderns\":3}}")
=> {"GuestOrder"=>{"GuestOrderId"=>1, "orderTime"=>"2012-04-25 18:28:30", "notes"=>"spicy",
"userId"=>14, "tableId"=>1, "batch"=>[{"items"=>[{"itemId"=>1, "quantity"=>4, "dishId"=>1},
{"itemId"=>2, "quantity"=>4, "dishId"=>3}, {"itemId"=>3, "quantity"=>3, "dishId"=>6}],
"placed"=>"2012-04-25 18:28:30", "batchId"=>1}], "numberOfAdults"=>1,
"numberOfChilderns"=>3}}
这里guest_orders有很多order_batches,order_batches有很多order_items
# == Schema Information
#
# Table name: guest_orders
#
# GuestOrderId :integer not null, primary key
# adults :integer
# children :integer
# orderTime :datetime
# tableId :integer
#
# Table name: order_batches
#
# batchId :integer not null, primary key
# placed :datetime
# guest_order_id :integer
#
# Table name: order_items
#
# itemId :integer not null, primary key
# quantity :integer
# dishId :integer
# order_batch_id :integer