Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 655
Luke Avatar asked Nov 29 '16 16:11

Luke


1 Answers

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.

like image 93
Luke Avatar answered Nov 13 '22 09:11

Luke