Rails 5 API POST创建参数为空 [英] Rails 5 API POST Create params empty

查看:92
本文介绍了Rails 5 API POST创建参数为空的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

感谢您关注此问题.我正在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对象为nil:

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

我的邮递员请求得到一个响应,表明.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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆