感谢您查看此问题。我在Rails 5中构建API,并且遇到了POST创建请求的问题。
基本上,当我的API获取它们时,我的参数是空的,不知道为什么。使用Postman发送此JSON对象:
{
"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对象为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
My Postman请求得到一个响应,说明.permit是一个未定义的哈希方法,我也在终端中看到:
"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'
之前我还没遇到过这个问题,所以我们非常感激任何见解。
答案 0 :(得分:4)
白名单需要对象类(在这种情况下是战斗)
params.require(:battle).permit(:winner_score, :loser_score, :winner_id, :loser_id)
答案 1 :(得分:0)
正如你所说,params空洞可能是因为你需要在RestClient
或Postman
中发送标题
Content-Type : Application/JSON