Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send an array with a POST request, with a parameter name for the array that contains an empty set of square brackets []?

So, Rails normally handles parsing of incoming Arrays sent via HTTP Post requests (forms), like this:

"Normally Rails ignores duplicate parameter names. If the parameter name contains an empty set of square brackets [] then they will be accumulated in an array." - Rails Guides

But when using Net::HTTP.Post to send a Post request to a third party service (API), then it seems this convention of handling arrays in HTTP Post requests is not followed.

This code:

data = {:categories => [one, two, three]}
http = Net::HTTP.new(uri.host, uri.port)
request = Net::HTTP::Post.new(uri.request_uri)
request.set_form_data(data)
response = http.request(request)

Then set_form_data will serialize the Array like this:

categories=one&categories=two&categories=three

And not like this (which I thought was the conventional Rails way):

categories[]=one&categories[]=two&categories[]=three

Why?

I can see that it has to do with the recent implementation of the URI.encode_www_form method that set_form_data uses. But what is the purpose deviating from the conventional Rails way?

And, more importantly, how do I easily modify this to send it in the latter way (without overloading a bunch of inherent Ruby/Rails methods)?

like image 956
Magne Avatar asked Oct 14 '25 23:10

Magne


1 Answers

I found out that the solution was as easy as changing the table name:

data = {'categories[]' => [one, two, three]}

It even works if other elements of the data hash are :symbols.

I'd still be curious to find out why Rails makes this "hack" necessary when using the Net::HTTPHeader::set_form_data method, to get Rails' otherwise conventional way of handling arrays in the url parameters.

like image 170
Magne Avatar answered Oct 17 '25 12:10

Magne



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!