2011-03-01 56 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编码字符。

相关问题