Rails 5 API POST 创建参数为空 [英] Rails 5 API POST Create params empty
问题描述
感谢您关注这个问题.我正在 Rails 5 中构建 API,并且在处理 POST 创建请求时遇到问题.
thanks for taking at look at this issue. I'm building an API in Rails 5, and having trouble with the a POST create request.
基本上,当我的 API 获取它们时,我的参数是空的,并且不知道为什么.使用 Postman 发送此 JSON 对象:
Basically, my params are empty by the time my API gets them and not sure why. Sending this JSON object with Postman:
{
"battle": {
"winner_score": 300,
"loser_score": 3,
"winner_id": 2,
"loser_id": 1
}
}
这是相关的控制器:
class Api::V1::BattlesController < ApplicationController
protect_from_forgery with: :null_session, if: Proc.new { |c| c.request.format.include? 'application/json' }
wrap_parameters format: [:json]
# POST /battles
def create
@battle = Battle.new(battle_params)
if @battle.save
render json: @battle, status: :created, location: @battle
else
render json: @battle.errors, status: :unprocessable_entity
end
end
private
# Only allow a trusted parameter "white list" through.
def battle_params
binding.pry
params.permit(:winner_score, :loser_score, :winner_id, :loser_id)
end
end
当我在 Battle_params 方法中点击 binding.pry 时,params 对象为零:
When I hit the binding.pry in the battle_params method, the params object is nil:
50: def battle_params
=> 51: binding.pry
52: params = params.to_h
53: params.permit(:winner_score, :loser_score, :winner_id, :loser_id)
54: end
params
=> nil
我的 Postman 请求得到一个响应,说 .permit 是一个未定义的散列方法,我也在终端中看到:
My Postman request gets a response that says .permit is an undefined method on the hash, which I also see in the terminal:
"status":500,"error":"Internal Server Error","exception":"#\u003cNoMethodError: undefined method `permit' for {}:Hash\u003e"
NoMethodError (undefined method `permit' for {}:Hash):
app/controllers/api/v1/battles_controller.rb:53:in `battle_params'
我以前从未遇到过这个问题,因此非常感谢您提供任何见解.
I haven't run across this issue before, so any insight is really appreciated.
推荐答案
白名单需要对象类(本例中的战斗)
The whitelisting needs the object class (battle in this case)
params.require(:battle).permit(:winner_score, :loser_score, :winner_id, :loser_id)
这篇关于Rails 5 API POST 创建参数为空的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!