首页 > 解决方案 > Rails 强参数 - 允许请求而无需密钥

问题描述

我正在研究 Rails API,并且在控制器中使用强参数。我有一个请求规范,它在一个模型上失败,但在所有其他模型上都有效。每个型号的控制器几乎都相同。

正如您在规范中看到的那样,请求正文应该是{ "tag": { "name": "a good name" }}. 但是,此规范使用{ "name": "a good name" }的应该是无效的,因为它缺少“标记”键。相同控制器功能的相同规格适用于许多其他型号。

另一个有趣的转折是,如果我将控制器的强参数更改为params.require(:not_tag).permit(:name)它会抛出一个错误,因为它不包含“not_tag”键。

控制器

class TagsController < ApplicationController
  before_action :set_tag, only: [:show, :update, :destroy]

  # Other methods...

  # POST /tags
  def create
    @tag = Tag.new(tag_params)

    if @tag.save
      render "tags/show", status: :created
    else
      render json: @tag.errors, status: :unprocessable_entity
    end
  end

  # Other methods...

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_tag
      @tag = Tag.find_by(id: params[:id])
      if !@tag
        object_not_found
      end
    end

    # Only allow a trusted parameter "white list" through.
    def tag_params
      params.require(:tag).permit(:name)
    end

    # render response for objects that aren't found
    def object_not_found
      render :json => {:error => "404 not found"}.to_json, status: :not_found
    end
end

请求规格

require 'rails_helper'
include AuthHelper
include Requests::JsonHelpers

RSpec.describe "Tags", type: :request do
  before(:context) do
    @user = create(:admin)
    @headers = AuthHelper.authenticated_header(@user)
  end

  # A bunch of other specs...

  describe "POST /api/tags" do
    context "while authenticated" do
      it "fails to create a tag from malformed body with 422 status" do
        malformed_body = { "name": "malformed" }.to_json
        post "/api/tags", params: malformed_body, headers: @headers
        expect(response).to have_http_status(422)
        expect(Tag.all.length).to eq 0
      end
    end
  end

# A bunch of other specs...

  after(:context) do
    @user.destroy
    @headers = nil
  end
end

标签: ruby-on-railsrspecstrong-parameters

解决方案


这种行为是因为在 Rails 6 中默认启用的ParamsWrapperwrap_parameters功能。将接收到的参数包装到嵌套哈希中。因此,这允许客户端发送请求而无需在根元素中嵌套数据。

例如,在名为 的模型中Tag,它基本上转换

{
  name: "Some name",
  age: "Some age"
}

{
  tag:
    {
      name: "Some name",
      age: "Some age"
    }
}

但是,正如您在测试中看到的那样,如果您将所需的密钥更改为not_tag,则包装会按预期中断 API 调用。

可以使用该config/initializers/wrap_parameters.rb文件更改此配置。在该文件中,您可以设置wrap_parameters format: [:json]wrap_parameters format: []禁止此类参数包装。


推荐阅读