0

这让我发疯

我需要链接格式为

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}])];

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

我怎样才能使这项工作?是控制器的问题还是视图的问题?

4

1 回答 1

1

JSON 中没有符号的概念(如 Ruby 中)。密钥必须是 JSON 中的字符串。在您的情况下,您似乎不需要密钥。你可以只拥有一个追随者 ID 和可追随者 ID 的数组。

于 2013-03-20T02:11:04.387 回答