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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5161579/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 00:33:57  来源:igfitidea点击:

rails - how to render a JSON object in a view

ruby-on-railsjsonruby-on-rails-3actionview

提问by AnApprentice

right now I'm creating an array and using:

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

render :json => @comments

This would be fine for a simple JSON object, but right now my JSON object requires several helpers which is breaking everything and requiring helper includes in the controller which seems to cause more problems than solved.

这对于一个简单的 JSON 对象来说很好,但是现在我的 JSON 对象需要几个助手,这破坏了一切,并且需要在控制器中包含助手,这似乎导致的问题比解决的问题还多。

So, how can I create this JSON object in a view, where I don't have to worry about doing anything or breaking anything when using a helper. Right now the way I'm making the JSON object in the controller looks little something like this? Help me migrate it to a view :)

那么,如何在视图中创建这个 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

Thanks!

谢谢!

采纳答案by Marcel Hymanwerth

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

我建议您在帮助程序本身中编写该代码。然后只需.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) %>

回答by JayCrossler

Or use:

或使用:

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

to escape out any html encoding characters.

转义任何 html 编码字符。

回答by Daniel Tsadok

<%= @comments.to_json %>

should do the trick too.

也应该这样做。