Sending array of nulls in json request - Rails 5

Viewed 1195

I need to send request to my Rails API with key like: ids: [null, 1, 2, null, 3]. Unfortunately Rails cuts all the nulls from this array so the params[:ids] returns [1, 2, 3]. I need those nulls in the array.

How can I prevent Rails from removing them? I can send empty string instead of null, but it's not very elegant.

3 Answers

In rails 5, intends to not have the same sql injection vulnerabilities and so have removed the deep_munge method that would change an empty array value to nil but have left in the configuration option which produces behavior best described by looking at the tests.

for more info

https://apidock.com/rails/v3.2.8/ActionDispatch/Request/deep_munge

https://til.hashrocket.com/posts/e1bed09363-deepmunge-i-hardly-knew-ye

In application.rb add below line

config.action_dispatch.perform_deep_munge = false

and restart the application

use json structure instead of array

replace

ids: [null, 1, 2, null, 3]

with

ids: {"0": null, "1": 1, "2": 2, "3": null, "4": 3}

And in controller access it like

params[:ids].values
[nil, 1, 2, nil, 3]

In different environment null value is interpreted differently.

I think that the best practice is to replace these entries according the result you want to achieve:

ids.map! { |id| id == null ? nullValue : id }.flatten!

Where nullValue is what you're expecting to have in the array.

Related