且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Rails 5 测试控制器未过滤的参数

更新时间:2023-09-28 21:34:34

ActionController::Parameters 的实例上调用 to_hto_hash 时发生此错误 没有任何允许的键(文档).

This error occurs when calling to_h or to_hash on an instance of ActionController::Parameters that doesn't have any permitted keys (documentation).

由于 ActionController::Parameters#slice 返回一个相同的实例,这段代码不会给你一个看起来像的散列:params.slice(:item, :section).

Since ActionController::Parameters#slice returns an instance of the same, this code does not give you a hash like it would seem: params.slice(:item, :section).

在大多数情况下,您可以在参数实例上使用 permit 而不是 slice.如果您想绕过 ActionController::Parameters 的安全访问白名单,您可以使用 permit! 并使用 ActionController::Parameters#slice,或者,如果您想在没有清理的情况下转换为哈希,您可以使用 to_unsafe_h.

In most cases you can use permit instead of slice on parameters instances. If you ever want to bypass the safe access whitelisting of ActionController::Parameters you can use permit! and use ActionController::Parameters#slice, or if you want to convert to a hash without sanitization you can use to_unsafe_h.