データベース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