Ruby on Rails: send javascript array of arrays to ruby controller

bdeonovic picture bdeonovic · Jun 26, 2012 · Viewed 8.9k times · Source

I would like to send a javascript array of arrays to my ruby controller. I am a bit lost. My question is in the controller. Here is what I have so far:

(totalChanges is an array of arrays. JSON.stringify(totalChanges) might look like this:

[[4,2,"","15"],[4,3,"","12"],[4,4,"","14"]]

app/views/index.html.erb:

<div id="dataTable" class="dataTable" style="width: 680px;height: 300px; overflow: scroll"></div>
<button>Save!</button>
<script>
    var first = true;
    var totalChanges = new Array();
    $("#dataTable").handsontable({
         //...some code that generates appropriate array totalChanges
    });
    var data = //..some code
    $("#dataTable").handsontable("loadData", data);
    $(function() {
            $( "button").button();
            $( "button" ).click(function() { 
                    alert("clicked"); 
                    $.ajax({
                            type: "POST",
                            url: "/qtl_table/save",
                            data: {total_changes: JSON.stringify(totalChanges)},
                            success: function() { alert("Success!"); }
                    });
            });
    });

</script>

app/controllers/qtl_table_controller.rb:

def save
  //Adding some things suggested by answers:
  logger.debug "\n#{params[:total_changes].first}, #{params[:total_changes][1]}\n"
  ar = JSON.parse(params[:total_changes])
end

I end up with these errors:

NoMethodError (You have a nil object when you didn't expect it!
You might have expected an instance of Array.
The error occurred while evaluating nil.first):

EDIT: I also had contentType: "application/json", and Accepts: "application/json" and when I took those out everything worked out. Thanks guys :)

Answer

KL-7 picture KL-7 · Jun 26, 2012

JSON.parse is your friend:

ar = JSON.parse(params[:total_changes])
#=> [[4, 2, "", "15"], [4, 3, "", "12"], [4, 4, "", "14"]]

Most likely you'll need to update your AJAX call to something like:

$.ajax({
  type: "POST",
  url: "/qtl_table/save",
  data: { total_changes: JSON.stringify(totalChanges) },
  success: function() { alert("Success!"); }
});

to give your array parameter total_changes name.