HanXu
HanXu

Reputation: 5597

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?

Upvotes: 10

Views: 9597

Answers (2)

claptimes
claptimes

Reputation: 1717

You'd have to convert the JSON to a string, but this would work:

/path/to/url?data[]=1&data[]=2&data[]=3

And in the controller, do something like:

params[:data].each_with_index do |data, index| 
   do_something_with_data
end

Upvotes: 1

Rob Dawson
Rob Dawson

Reputation: 1347

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'
       }
     );

Upvotes: 3

Related Questions