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

1

12

I'm having a problem when sending a controller params that look like this:

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

The method only sees { id: "1" } and the entire stuff parameter is dropped.

This can be changed if there are any values in the arrays. But say there are values in all the arrays except for the key "C", they will all be there besides "C" like:

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

I'm falling into this problem upgrading from Rails 4.2.x -> 5.0.0 Any suggestions on what is happening here? I've seen a few articles/issues around munging parameters, but I'm not sure if that's the issue because in their example table of how munging works is {person: []} becomes {person: nil}, where the person param isn't dropped completely.

Aminta answered 29/11, 2016 at 16:28 Comment(0)
A
13

From @sgrif in the GH community:

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.

Adding as: :json didn't end up working for me, but adding @request.headers["Content-Type"] = 'application/json' at the beginning of the test did.

Aminta answered 1/12, 2016 at 14:45 Comment(3)
Thanks, that header tweak does the trick for me too. Do we have any clue why as: :json solution isn't working?Gainor
I didn't pry into that any further, sorry.Aminta
Thanks for sharing this!Kazmirci

© 2022 - 2024 — McMap. All rights reserved.