rails – 如何在视图中呈现JSON对象

现在我正在创建一个数组并使用:

render :json => @comments 

这对于一个简单的JSON对象来说没什么问题,但是现在我的JSON对象需要几个帮助器,它们破坏了所有内容并且需要在控制器中包含帮助器,这似乎会导致更多问题而不是解决。

那么,我如何在视图中创建这个JSON对象,在使用帮助器时我不必担心做任何事情或破坏任何东西。 现在我在控制器中制作JSON对象的方式看起来像这样的东西? 帮我把它迁移到视图:)

 # Build the JSON Search Normalized Object @comments = Array.new @conversation_comments.each do |comment| @comments < 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 

谢谢!

我建议您在帮助程序中编写该代码。 然后在数组上使用.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) %> 

或使用:

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

逃避任何html编码字符。

 <%= @comments.to_json %> 

也应该做的伎俩。