rails-如何在视图中呈现JSON对象 [英] rails - how to render a JSON object in a view

查看:94
本文介绍了rails-如何在视图中呈现JSON对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

谢谢!

解决方案

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

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.

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 :)

# 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!

解决方案

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

这篇关于rails-如何在视图中呈现JSON对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆