我正在尝试从rails应用程序中的d3.js给我漂亮的图表。我尝试的其中一张图是forced directed graph。为了创建它,JSON需要采用
格式{
"nodes":[
{"name":"Myriel"},
{"name":"Napoleon"},
{"name":"Mlle.Baptistine"},
{"name":"Mme.Magloire"}
],
"links":[
{"source":1,"target":0,"value":1},
{"source":2,"target":0,"value":8},
{"source":3,"target":0,"value":10},
{"source":3,"target":2,"value":6}
]
}
我目前使用此查询从我的数据库中生成了JSON:
User.joins("INNER JOIN relationships ON users.id = relationships.user_id").select(" users.name, relationships.source, relationships.target,relationships.value")
在控制器中创建如下
def index
render :json => User.joins("INNER JOIN relationships ON users.id = relationships.user_id").select(" users.name, relationships.source, relationships.target,relationships.value")
end
end
,结果如下:
[{"name":"Myriel","source":121,"target":1,"value":1},{"name":"Napoleon","source":119,"target":2,"value":2}, {"name":"Myriel","source":121,"target":1,"value":2},{"name":"Myriel","source":121,"target":3,"value":1},{"name":"Mlle.Baptistine","source":122,"target":2,"value":3}]
有没有一种简单的方法可以将我的JSON映射到我需要的东西?
答案 0 :(得分:2)
您可以为User模型编写一个类方法,该方法将根据需要返回json。
def get_json
json_data = User.joins("INNER JOIN relationships ON users.id = relationships.user_id").select(" users.name, relationships.user_id, relationships.target,relationships.value")
{
'nodes' => json_data.collect {|json| json.slice('name')},
'links' => json_data.collect {|json| json.slice('source', 'target', 'value')}
}
end
答案 1 :(得分:1)
如另一个答案所示,创建一个类方法:
class User
def self.including_relationships
User.joins("INNER JOIN relationships ON users.id = relationships.user_id").select("users.name, relationships.user_id, relationships.target,relationships.value").each_with_object(Hash.new{|h, k| h[k] = []}) do |a, obj|
obj['nodes'] << a.slice('name')
obj['links'] << a.slice('source', 'target', 'value')
end
end
end
然后在你的控制器中:
def index
render :json => User.including_relationships
end
我将方法命名为including_relationships
,因为它并没有真正创建JSON而是将数据转换为Hash
对象,您可以根据需要对其进行命名。