views:

332

answers:

2

Hi,

how do I pass a 2-dimensional array from javascript to ruby, please? I have this on client side:

function send_data() {
    var testdata = {
        "1": {
            "name": "client_1",
            "note": "bigboy"
        },
        "2": {
            "name": "client_2",
            "note": "smallboy"
        }
    }

    console.log(testdata);
    $.ajax({
      type: 'POST',
      url: 'test',
      dataType: 'json',
      data: testdata
    });
  }

and this on server side:

post '/test' do p params end

but I can't get it right. The best I could get on server side is something like

{"1"=>"[object Object]", "2"=>"[object Object]"}

I tried to add JSON.stringify on client side and JSON.parse on server side, but the first resulted in

{"{\"1\":{\"name\":\"client_1\",\"note\":\"bigboy\"},\"2\":{\"name\":\"client_2\",\"note\":\"smallboy\"}}"=>nil}

while the latter has thrown a TypeError - can't convert Hash into String.

Could anyone help, or maybe post a short snippet of correct code, please? Thank you

A: 

You may want to build up the JSON manually, on the javascript side:

[[{'object':'name1'},{'object':'name2'}],[...],[...]]

This will build an array of arrays with objects.

It may look like this:

testdata = [[{
        "1": {
            "name": "client_1",
            "note": "bigboy"
        }],
        [{"2": {
            "name": "client_2",
            "note": "smallboy"
        }]
    }]

I may have something off here, but this should be close to what it would look like.

James Black
A: 

I'm not sure if this will help but I've got two thoughts: serialize fields and/ or iterate the array.

I managed to get a json array into activerecord objects by setting serializing the fields which had to store sub-arrays:

class MyModel < ActiveRecord::Base
  serialize :tags
end

and using an iterator to process the json array:

f = File.read("myarrayof.json")
jarray = JSON.load(f)
jarray.each { |j| MyModel.create.from_json(j.to_json).save }

The conversion back-and-forth seems a bit cumbersome but I found it the most obvious way to handle the array.

RobinGower