railsgod railsgod - 8 months ago 36
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 %>];
$.plot("#flot-placeholder", [ fail_builds ]);

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!



@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 %>");