我試圖通過捲曲在JSON發送POST請求在Ruby on Rails的JSON格式的POST請求。我想知道如何在控制器中解析此請求並將其保存在數據庫中。我爲玩家創建了控制器和模型。如何分析在軌
下面是curl命令 -
curl -i -X POST -H "Content-Type: application/json" "localhost:3000/app/v2/player" -d '{
"url": "app/v2/players.json",
"para": {
"player": {
"player_id": 51275,
"email": "[email protected]",
"total_won": "1890000.00",
"pr_costs": "29.00",
"payment_method": "VISA",
"games": [
{
"name": "AvsB",
"matches": 1,
"value": 1100,
"category": "Cricket",
"subcategory": "Test",
"tags": [
"Aus",
"Melbourne"
],
"game_id": 12
},
{
"name": "CvsD",
"matches": 1,
"value": 790,
"category": "Cricket",
"subcategory": "T20",
"tags": [
"T20",
"20over",
"worldcup"
],
"game_id": 7
}
]
}
}
}'
下面是我的球員控制器 -
module App
module V2
class PlayersController < ApplicationController
def create
@player = Player.new(params[[:para][:player][:player_id]].first)
if @player.save
render json: @player, status: 201, location: @player
else
render json: @player.errors, status: 422
end
end
private
def player_params
#params.require(:player).permit(:url, :player_id, :email, :total_won, :pr_costs, :payment_method)
params.fetch(:url,:para, {}).permit(:player_id, :email, :total_won, :pr_costs, :payment_method)
end
end
end
end
下面是我的球員的典範 -
class Player < ActiveRecord::Base
has_many :games, dependent: :destroy
validates :player_id, presence: true
attr_accessor :url,:para
end
目前我得到以下錯誤同時啓動捲曲命令 -
TypeError (no implicit conversion of Symbol into Integer):
app/controllers/app/v2/players_controller.rb:21:in `[]'
app/controllers/app/v2/players_controller.rb:21:in `create'
我如何可以讀取JSON數據,並創建記錄玩家在創建功能以及相關的遊戲任何指針將不勝感激。我還沒有創建遊戲模型,但它的結構與JSON數據類似。另外一個玩家有很多遊戲,一個遊戲將屬於一個玩家。
在此先感謝!
爲什麼你有一個額外的'[]'的'params' 嘗試'PARAMS [:對] [:玩家]' – gmaliar