2012-07-02 21 views
0

我想將我的模型渲染爲json,並在使用acts_as_tree時包含它的節點。我發現這個帖子,它幫助了很多:acts_as_tree and to_json or from_json在rails控制器中實現erb代碼?

我唯一的問題是如何在我的控制器中實現這一點。我想在我的控制器中返回json。

到目前爲止,我有這樣的:

respond_to :json, :html 

    def index 
    @categories = Category.all 
    respond_with(@categories) 
    end 

但在返回之前@categories我想調用這個就可以了:<%= @categories.select { |c| c.root? && !c.leaf? }.collect { |c| category_to_spacetree_json(c) }.to_json.html_safe %>但它看起來像這隻能從視圖中調用。

如何從我的控制器執行此操作?

謝謝!

+0

Rails的流程是這樣的:控制器 - >模型 - >視圖所以,你必須遵循這一點。並使用'respond_to:json'而不是'respond_to:json,:html'只返回:json格式 – RAJ

回答

0

你試過嗎?

在控制器:

def index 
    @categories = Category.all 
    respond_with(@categories.select{ |c| c.root? && !c.leaf? }.collect{ |c| category_to_spacetree_json(c) }) 
end 

在視圖:

<%= @categories.html_safe %>