2012-03-30 89 views
8

我使用祖先製作目標樹。我想用json將該樹的內容發送到瀏覽器。如何從祖先生成json樹

我的控制器是這樣的:

@goals = Goal.arrange 
respond_to do |format| 
    format.html # index.html.erb 
    format.xml { render :xml => @goals } 
    format.json { render :json => @goals} 
end 

當我打開JSON文件,我得到這樣的輸出:

{"#<Goal:0x7f8664332088>":{"#<Goal:0x7f86643313b8>":{"#<Goal:0x7f8664331048>":{"#<Goal:0x7f8664330c10>":{}},"#<Goal:0x7f8664330e68>":{}},"#<Goal:0x7f86643311b0>":{}},"#<Goal:0x7f8664331f70>":{},"#<Goal:0x7f8664331d18>":{},"#<Goal:0x7f8664331bd8>":{},"#<Goal:0x7f8664331a20>":{},"#<Goal:0x7f86643318e0>":{},"#<Goal:0x7f8664331750>":{},"#<Goal:0x7f8664331548>":{"#<Goal:0x7f8664330aa8>":{}}} 

我怎樣才能使目標對象的內容的JSON文件?

我已經試過這樣:

@goals.map! {|goal| {:id => goal.id.to_s} 

,但它不工作,因爲@goals是一個有序的哈希值。

+1

如果格式碼作爲代碼(縮進由4位,或者與反引號包圍['\''])你沒有隨機除去''<' and '>第http://stackoverflow.com/editing-help – 2012-03-30 13:35:54

+0

謝謝。修復。 – 2012-03-30 13:39:57

回答

10

我從https://github.com/stefankroes/ancestry/issues/82的用戶tejo那裏得到了一些幫助。

解決的辦法是把這個方法的目標模式:

def self.json_tree(nodes) 
    nodes.map do |node, sub_nodes| 
     {:name => node.name, :id => node.id, :children => Goal.json_tree(sub_nodes).compact} 
    end 
end 

,然後使控制器是這樣的:

@goals = Goal.arrange 
respond_to do |format| 
    format.html # index.html.erb 
    format.xml { render :xml => @goals } 
    format.json { render :json => Goal.json_tree(@goals)} 
end 
+2

這似乎是你不需要祖先然後 – SET 2013-03-08 10:33:10

+1

我是唯一一個在日誌中獲取消息的人嗎? 'N + 1查詢檢測 Directory => [:children] 添加到您的查找器::includes => [:children] N + 1查詢方法調用堆棧' 我正在使用'closure_tree'。 – cantonic 2015-07-24 01:48:38

2

從這個https://github.com/stefankroes/ancestry/wiki/arrange_as_array

def self.arrange_as_json(options={}, hash=nil) 
    hash ||= arrange(options) 
    arr = [] 
    hash.each do |node, children| 
    branch = {id: node.id, name: node.name} 
    branch[:children] = arrange_as_json(options, children) unless children.empty? 
    arr << branch 
    end 
    arr 
end 
0

啓發有一天我遇到了這個問題(祖先2.0.0)。我修改了Johan的答案以滿足我的需求。我有三個使用祖先的模型,因此擴展OrderedHash以添加as_json方法而不是將json_tree添加到三個模型是有意義的。

由於此主題非常有幫助,我以爲我會分享此修改。

其設置爲一個模塊或猴子修補的ActiveSupport :: OrderedHash

def as_json(options = {}) 
    self.map do |k,v| 
     x = k.as_json(options) 
     x["children"] = v.as_json(options) 
     x 
    end 
end 

我們稱之爲模型,並使用它的默認JSON行爲。不知道是否應該撥打 _json或作爲 _json。我在這裏使用了as_json,它在我的代碼中起作用。

在控制器

... 
format.json { render :json => @goal.arrange} 
...