ruby-on-rails - Rails 强参数 - 允许请求而无需密钥
问题描述
我正在研究 Rails API,并且在控制器中使用强参数。我有一个请求规范,它在一个模型上失败,但在所有其他模型上都有效。每个型号的控制器几乎都相同。
正如您在规范中看到的那样,请求正文应该是{ "tag": { "name": "a good name" }}
. 但是,此规范使用{ "name": "a good name" }
的应该是无效的,因为它缺少“标记”键。相同控制器功能的相同规格适用于许多其他型号。
另一个有趣的转折是,如果我将控制器的强参数更改为params.require(:not_tag).permit(:name)
它会抛出一个错误,因为它不包含“not_tag”键。
- 红宝石:2.6.5p114
- 导轨:6.0.1
- 预期响应状态:422
- 收到响应状态:201
控制器
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
解决方案
这种行为是因为在 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: []
禁止此类参数包装。
推荐阅读
- javascript - NumberFormatter:在不同语言环境中带有减号的奇怪行为
- boost - 使用 Posix 消息队列提升消息队列
- python - 如何提取此类音频中的属性?
- concurrency - Lambda SQL Server RDS 连接泄漏
- c# - 排序列表
和重复的键 - reactjs - 为什么向 ag-grid-react 添加一列会导致所有单元格重新呈现?
- html - 打开角度材料对话框时,父组件应处于活动状态
- python - 无效的密码格式或未知的散列算法。在 django 休息框架中
- python - 无法将数据写入 CSV 文件
- node.js - Module.create 不从输入中获取数据,req.body 为空