现在,我正在创建一个数组,并使用:
render :json => @comments
这对于一个简单的JSON对象来说很好,但是现在我的JSON对象需要几个helper,这破坏了一切,并且需要在控制器中包含helper include,这似乎导致了更多的问题而不是解决了问题。
那么,我如何在视图中创建这个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
谢谢!
发布于 2011-03-02 07:19:33
我建议您在helper本身中编写该代码。然后在数组上使用.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) %>
发布于 2013-01-28 04:00:48
或使用:
<%= raw(@comments.to_json) %>
来转义任何html编码字符。
发布于 2011-03-02 07:26:26
<%= @comments.to_json %>
应该也能做到这一点。
https://stackoverflow.com/questions/5161579
复制相似问题