rails - how to render a JSON object in a view

99封情书 提交于 2019-12-03 05:57:50

I would recommend that you write that code in an helper itself. Then just use the .to_json method on the array.

# 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) %>

Or use:

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

to escape out any html encoding characters.

Daniel Tsadok
<%= @comments.to_json %>

should do the trick too.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!