Rails 5 params with an object having empty arrays when values ​​are discarded

I had a problem sending controller parameters that look like this:

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

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

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

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

I get into this problem when upgrading from Rails 4.2.x β†’ 5.0.0 Any suggestions on what's going on here? I saw several articles / problems around brute force options , but I'm not sure that this problem is because in their table of examples of how munging works {person: []} becomes {person: nil} , where the personal parameter is not completely discarded.

+7
arrays ruby-on-rails ruby-on-rails-5 strong-parameters
source share
1 answer

From @sgrif in the GH community:

This is the expected behavior. It is not possible 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 do not encode their parameters, they just pass the hash through directly. In Rails 5, it encodes them. If your regulator takes care of empty arrays, you are probably dealing with JSON requests. You can do this in your test with :: json. If you are simply dealing with form input, you will never get an empty array.

Adding as: :json did not finish the job for me, but adding @request.headers["Content-Type"] = 'application/json' at the start of the test did.

+6
source share

All Articles