18

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

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

谢谢!

4

3 回答 3

27

或使用:

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

转义任何 html 编码字符。

于 2013-01-27T20:00:48.487 回答
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) %>
于 2011-03-01T23:19:33.363 回答
7
<%= @comments.to_json %>

也应该这样做。

于 2011-03-01T23:26:25.707 回答