2013-01-04 38 views
1

我創建了一個需要使用JSON的POST的API。此API用於在請求期間創建多個新項目。我正試圖在下面顯示的JSON中提取特定的信息。Rails:使用嵌套JSON的POST API

的JSON結構如下所示:

{ "Items": [ {"item_id": 1 }, { "item_id": 2 }. { "item_id": 3 }, ... ] } 

控制器裏面,我有以下幾點:

def create 
    all_items = params[:items] 
    ... 
    # Need something here to extract the item_id's from all_items and 
    # saved into a variable called item_id 
    # Possibly a loop to do this 
    new_item = Item.new(item_id) 
    new_item.save 
    render :json => {'Message' => 'Successfully created #{item_id}'}.to_json, :status => 200 
end 

我已經使用ActiveSupport::JSON.decode(all_items)試過,但我得到一個錯誤說cant convert Array into String。不知道我是否需要使用這個。

非常感謝您的幫助!

+0

它是如何做到的POST操作?你能提供表單還是ajax代碼? –

回答

2
all_items.each do |item| 
    new_item = Item.new(item["item_id"]) 
    new_item.save 
end 
+0

非常棒,非常感謝! – Rahul