Rails 5 个参数,对象具有空数组,因为值被删除

Rails 5 params with object having empty arrays as values are dropped

我在发送如下所示的控制器参数时遇到问题:

{ id: "1", stuff: {"A" => [], "B" => [], "C" => [], "D" => []} }

该方法只看到 { id: "1" } 并且删除了整个 stuff 参数。

如果数组中有任何值,这可以更改。但是假设除了键 "C" 之外的所有数组中都有值,除了 "C" 之外它们都会存在,例如:

{ id: "1", stuff: {"A" => ["1"], "B" => ["2", "3"], "D" => ["4"]} }

我从 Rails 4.2.x -> 5.0.0 升级时遇到了这个问题 对这里发生的事情有什么建议吗?我在 munging parameters 周围看到了一些 articles/issues,但我不确定这是否是问题所在,因为在他们的例子中,table 的 munging 工作方式是 {person: []} 变成 {person: nil},其中 person 参数没有完全删除。

来自 GH 社区的@sgrif:

This is the expected behavior. There is no way to encode an empty array using an HTML form (e.g. Content-Type: url-form-encoded). The reason your tests passed in Rails 4.2 is because controller tests did not encode their parameters, they simply passed the hash through directly. In Rails 5 it encodes them. If your controller cares about empty arrays, it's likely that you are dealing with JSON requests. You can do that in your test with as: :json. If you're just dealing with form input, you will never receive an empty array.

添加 as: :json 最终对我不起作用,但在测试开始时添加 @request.headers["Content-Type"] = 'application/json' 确实有效。