Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to indicate empty array in HTTP request query params?

This is the way Rails accepts arrays in query parameters:

PUT /resource.json?sport_ids[]=133&sport_ids[]=64&sport_ids[]=71 ...

I tried to google this question but didn't find any explicit docs on it:

How to tell Rails that we want sport_ids to become empty (pass empty array of sport_ids via query parameters) ?

like image 662
Stanislav Pankevich Avatar asked Aug 13 '26 01:08

Stanislav Pankevich


1 Answers

  • HTTP requests can have only variables on the url itself. That's a limitation feature of HTTP, not Rails.

  • Take a look at How Does Rack Parse Query Params? With Parse_nested_query to figure out how rails collects the variables into an array, it won't run out of the box in case of an empty array.

You can avoiding sending the params["sport_ids"] and patch your controller with:

params["sport_ids"] ||= []

The best practice to use put/post requests, is passing such data in the request body (json/xml) like:

  {
    "sport_ids": []
  }

Or with data as:

//...
  {
    "sport_ids": [133, 64, 71]
  }
//...

For more info about HTTP request steps, check Running a HTTP request with rails.

like image 170
mohameddiaa27 Avatar answered Aug 15 '26 14:08

mohameddiaa27



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!