So, I'm building an API in Ruby on Rails and I'm trying to force an array to be sent through ajax.
It seems quite an easy task if it wasn't for the fact that the array is being received as an associative array other than regular array!
Basically an array with objects like:
[
{
"shipping_id":"1",
"option":"1"
},
{
"shipping_id":"2",
"option":"2"
}
]
becomes:
{"0"=>{"shipment_id"=>"1", "option"=>"1"}, "1"=>{"shipment_id"=>"2", "option"=>"2"}}
instead of
[{"shipping_id"=>"1", "option"=>"1"}, {"shipping_id"=>"2", "option"=>"2"}]
This is the JS I'm using to test the API:
function select_shipping(){
obj1 = {
"shipment_id": "1",
"option": "1"
};
obj2 = {
"shipment_id": "2",
"option": "2"
};
var shipments = [obj1, obj2];
var payload = {
user_options: shipments
}
$.post('/shipping/calculate/select', // url
payload, // data to be submit
function(data, status, jqXHR) {// success callback
console.log(data);
})
}
How can I transform my payload to go as a regular array instead of associative?
foo[0][foo]=barthats because if you encode it asfoo[][foo]=barRack has no way of knowing which hash the key belongs to. Also "associative arrays" are not a thing in Ruby - that's just a hash, and if you want to "cast" it into an array you just callhash.valuesand this is automatically done with strong parameters.