【问题标题】:Rails 5 API POST Create params emptyRails 5 API POST 创建参数为空
【发布时间】:2017-01-11 08:02:14
【问题描述】:

感谢您关注这个问题。我正在 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

我的 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'

我以前没有遇到过这个问题,因此非常感谢任何见解。

【问题讨论】:

  • 你试过params.require(:battle).permit(whitelist_items)

标签: ruby-on-rails json ruby api ruby-on-rails-5


【解决方案1】:

白名单需要对象类(本例为battle)

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

【讨论】:

    【解决方案2】:

    正如你所说,参数变空可能是因为你需要在RestClientPostman 中发送标头

    Content-Type : Application/JSON
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-01-24
      • 2014-01-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-08-09
      相关资源
      最近更新 更多