2015-06-20 71 views
0

我想重命名列,一旦它們出來的數據庫查詢,所以我可以讓他們進入一個d3.js圖形正確的格式。這要求這些字段被命名爲源,目標,值。如何重命名字段進入json散列

def self.including_relationships 
    User.select(:follower_id,:followed_id,:value) 
     #How do I rename the fields from the line above to the fields below 
     obj['links'] << a.slice('source', 'target', 'value') 
    end 
    end 

回答

2
User.select('follower_id, followed_id, value').map(&:attributes) 

會給你喜歡波紋管哈希的陣列。

[{"follower_id" => 1, "followed_id" => 2, "value" => 1}, 
{"follower_id" => 1, "followed_id" => 2, "value" => 1}, 
.......... 
{"follower_id" => 1, "followed_id" => 2, "value" => 1},] 

它可以存儲爲一個JSON鑄造它。

> [{"follower_id" => 1, "followed_id" => 2, "value" => 1}].to_json 
=> "[{\"follower_id\":1,\"followed_id\":2,\"value\":1}]" 
+0

這是如何根據問題重新命名字段源,目標,值? –

+0

User.select('follower_id as source,followed_id as target,value')。map(&:attributes)將執行這些操作。 –

1

你可以使用ActiveModel::SerializersJBuilder定製JSON輸出,但你應該考慮,而不是在JavaScript中操縱數據。

通過這樣做可以避免服務器端API與您使用的任何圖形庫之間的強大聯接。 您的API輸出不應該由您如何顯示數據來控制。

使用jQuery簡化示例:

var promise = $.getJSON('/users.json'); 
promise.then(function(data){ 
    return jQuery.map(data, function(user){ 
    return { 
     target: user.follower_id, 
     source: user.followed_id, 
     value: user.value 
    } 
    }).toArray(); 
}); 
promise.done(function(data){ 
    // draw the graph. 
});