Rails不会在json中输出数据

时间:2013-03-19 17:05:13

标签: javascript json ruby-on-rails-3

这让我发疯了

我需要链接格式为

links = [{source: 1, target: 2}, {..}, ...]

控制器代码:

  @edges = []
     Follow.where("followable_type= 'User'").map do |x|
      @edges << {source: x.follower_id, target: x.followable_id}
     end

查看代码(在javascript中):

var links = [(<%= @edges.to_json %>)];

html源代码中的输出是

var links = [([{&quot;source&quot;:2,&quot;target&quot;:3},{&quot;source&quot;:2,&quot;target&quot;:1},{&quot;source&quot;:8,&quot;target&quot;:1},{&quot;source&quot;:1,&quot;target&quot;:8},{&quot;source&quot;:17,&quot;target&quot;:13},{&quot;source&quot;:8,&quot;target&quot;:13},{&quot;source&quot;:8,&quot;target&quot;:3},{&quot;source&quot;:13,&quot;target&quot;:3},{&quot;source&quot;:3,&quot;target&quot;:2},{&quot;source&quot;:39,&quot;target&quot;:13},{&quot;source&quot;:3,&quot;target&quot;:39},{&quot;source&quot;:15,&quot;target&quot;:1},{&quot;source&quot;:1,&quot;target&quot;:15},{&quot;source&quot;:3,&quot;target&quot;:1},{&quot;source&quot;:3,&quot;target&quot;:8},{&quot;source&quot;:3,&quot;target&quot;:13},{&quot;source&quot;:21,&quot;target&quot;:3},{&quot;source&quot;:13,&quot;target&quot;:21},{&quot;source&quot;:13,&quot;target&quot;:39},{&quot;source&quot;:21,&quot;target&quot;:13},{&quot;source&quot;:21,&quot;target&quot;:27},{&quot;source&quot;:27,&quot;target&quot;:13},{&quot;source&quot;:1,&quot;target&quot;:3},{&quot;source&quot;:1,&quot;target&quot;:39},{&quot;source&quot;:1,&quot;target&quot;:2},{&quot;source&quot;:1,&quot;target&quot;:13},{&quot;source&quot;:1,&quot;target&quot;:21},{&quot;source&quot;:1,&quot;target&quot;:27}])];

所以我认为我应该在那里输入html_safe ..这会给出

var links = [([{"source":2,"target":3},{"source":2,"target":1},{"source":8,"target":1},{"source":1,"target":8},{"source":17,"target":13},{"source":8,"target":13},{"source":8,"target":3},{"source":13,"target":3},{"source":3,"target":2},{"source":39,"target":13},{"source":3,"target":39},{"source":15,"target":1},{"source":1,"target":15},{"source":3,"target":1},{"source":3,"target":8},{"source":3,"target":13},{"source":21,"target":3},{"source":13,"target":21},{"source":13,"target":39},{"source":21,"target":13},{"source":21,"target":27},{"source":27,"target":13},{"source":1,"target":3},{"source":1,"target":39},{"source":1,"target":2},{"source":1,"target":13},{"source":1,"target":21},{"source":1,"target":27}])];

哪个更好,但每个键都是一个字符串..我需要它不是字符串

我该如何使这项工作?是控制器或视图中的问题吗?

1 个答案:

答案 0 :(得分:1)

JSON中没有符号概念(如Ruby中)。密钥必须是JSON中的字符串。在您的情况下,您似乎不需要密钥。您可以拥有一系列关注者ID和可跟随的ID。