简体   繁体   中英

Rails 5 API POST Create params empty

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.

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
  }
}

Here's the relevant controller:

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

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

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.

白名单需要对象类(在本例中为战斗)

params.require(:battle).permit(:winner_score, :loser_score, :winner_id, :loser_id)

正如您所说的,params越来越空了,可能是因为您需要使用以下命令在RestClientPostman发送标头:

Content-Type : Application/JSON

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM