Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to POST an array in Rails

I want to POST a data as JSON to the controller

in javascript, the data is an array, for example, a = [1,2]

then I POST, say

$.post('user/data', {'data' : a})

in the user controller, I get the data from params.

However, when I retrieve params[:data], I got a hash:

{"0"=>1, "1"=>2}

rather then an array!

so I have to convert the hash into an array manually.

Is there a method to pass the exact array to the controller?

like image 601
HanXu Avatar asked Feb 05 '12 14:02

HanXu


1 Answers

I had a similar problem recently. My fix was to send json content instead of the default form encoded.

I used

 $.ajax(
 {
   type: "POST", 
   url: url, 
   data: JSON.stringify(data), 
   dataType: "json", 
   contentType: 'application/json'
 }
 );

In your example this could be done as:

$.ajax(
       {
         type: "POST", 
         url: 'user/data', 
         data: JSON.stringify({'data' : a}), 
         dataType: "json", 
         contentType: 'application/json'
       }
     );
like image 175
Rob Dawson Avatar answered Sep 20 '22 07:09

Rob Dawson