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

AnA*_*ice 17 json ruby-on-rails actionview ruby-on-rails-3

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

render :json => @comments
Run Code Online (Sandbox Code Playgroud)

这对于一个简单的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
Run Code Online (Sandbox Code Playgroud)

谢谢!

Jay*_*ler 23

或使用:

<%= raw(@comments.to_json) %> 
Run Code Online (Sandbox Code Playgroud)

逃避任何html编码字符.


Mar*_*rth 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) %>
Run Code Online (Sandbox Code Playgroud)


Dan*_*dok 6

<%= @comments.to_json %>
Run Code Online (Sandbox Code Playgroud)

也应该做的伎俩.