2011-03-01 76 views
16

現在我創建一個數組,並使用:軌道 - 如何呈現一個JSON對象在視圖中

render :json => @comments 

這將是罰款,一個簡單的JSON對象,但現在我的JSON對象需要幾個正在破壞一切並需要幫手的幫手包括在控制器中,這似乎會導致更多的問題而不是解決。

那麼,如何在一個視圖中創建這個JSON對象,我不必擔心在使用助手時做任何事情或破壞任何東西。現在我使控制器中的JSON對象看起來像這樣?幫我將它遷移到視圖:)

# Build the JSON Search Normalized Object 
@comments = Array.new 

@conversation_comments.each do |comment| 
    @comments << { 
    :id => comment.id, 
    :level => comment.level, 
    :content => html_format(comment.content), 
    :parent_id => comment.parent_id, 
    :user_id => comment.user_id, 
    :created_at => comment.created_at 
    } 
end 

render :json => @comments 

謝謝!

+0

有點困惑於「需要幾個幫手」,什麼幫手,做什麼? – macarthy 2011-03-01 23:19:52

+0

html_format是用戶simple_format和auto_link的幫手。這是所有麻煩的地方。 – AnApprentice 2011-03-01 23:22:31

+1

請按照[這些指導方針](http://stackoverflow.com/questions/2088280/in-rails-how-do-you-render-json-using-a-view/2088378#2088378) – 2011-03-01 23:29:26

回答

13

我會建議你在助手本身編寫代碼。然後,只需在陣列上使用.to_json 方法。

# application_helper.rb 
def comments_as_json(comments) 
    comments.collect do |comment| 
    { 
     :id => comment.id, 
     :level => comment.level, 
     :content => html_format(comment.content), 
     :parent_id => comment.parent_id, 
     :user_id => comment.user_id, 
     :created_at => comment.created_at 
    } 
    end.to_json 
end 

# your_view.html.erb 
<%= comments_as_json(@conversation_comments) %> 
+0

等等...是否存在在幫助器裏面意味着它可以使用像simple_format等不需要包含的東西? – AnApprentice 2011-03-01 23:22:10

+0

如果我這樣做了,html_format使用simple_format和auto_link是一個問題? – AnApprentice 2011-03-01 23:22:52

+0

我假設你發現現在回答自己 - 但是,你不需要在助手中明確包含其他助手。注意:這要求您的ApplicationController具有'helper:all'(默認)。 – 2011-03-02 00:32:19

6
<%= @comments.to_json %> 

應該做的伎倆。

22

或使用:

<%= raw(@comments.to_json) %> 

逃脫了任何HTML編碼字符。