railsgod railsgod - 3 months ago 14
Ruby Question

Convert Array of Objects to Javascript Rails

I'm trying to convert an array of Builds called @builds to a javascript array, doing it this way:

<script type="text/javascript">
$(function() {
var fail_builds = [];
var builds = [<%= raw @builds.to_json %>];
fail_builds.push([6,7],[5,builds.length],[1,2]);
$.plot("#flot-placeholder", [ fail_builds ]);
});
</script>


But builds.length no matter what, builds.length will return 1, even though roughly 50 builds are stored in @builds. Here is the schema for the Build model if that might help:

t.string "build_name"
t.string "status"
t.string "test_type"
t.string "target_branch"
t.datetime "time_started"
t.datetime "time_finished"
t.datetime "time_queued"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false


Thanks in advance!

Answer

Say

@builds = [1, 2, 3, 4, 5]

@builds.to_json will evaluate to "[1,2,3,4,5]" and thus your JS will end up looking like this:

var builds = [[1,2,3,4,5]];

An array of an array whose length is 1.

If you are sending JSON strings to the view you should be using JSON.parse() instead.

var builds = JSON.parse("<%= @builds.to_json %>");
Comments