控制器中的include_root_in_json [英] include_root_in_json from controller

查看:132
本文介绍了控制器中的include_root_in_json的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将结果返回到json不包含根的视图.

I'm trying to return a result to a view where the json does not include the root.

我不想为此模型的所有操作设置此设置,因此正尝试避免设置

I don't want to set this on all actions for this model,so therefore am trying to avoid setting


ActiveRecord.Base.include_root_in_json = false

我希望我能做


@task = Tasks.all
@task.include_root_in_json = false

要获得我需要的响应,但这似乎不起作用,请为#返回一个未定义的方法include_root_in_json =

有没有很好的方法呢?

To get the response I need, but that doesn't seem to be working, returning an 'undefined method include_root_in_json= for #

Is there a nice way of doing this??

推荐答案

现在是一个老问题,但是答案没有更新,并且 Rails 3.2填补了空白(

It's an old question now, but the answers were not updated, and Rails 3.2 filled the gap (Rails source)

现在,使用Rails 3.2,您可以使用:

my_model.to_json(:root => false)

如果您不希望包含根密钥.

if you don't want the root key to be included.

当我刚刚使用数组对其进行测试时,它会变得更好,所以您可以这样做:

It gets even better as I just tested it with an array, so you can do:

Model.all.to_json(:root => true)

这篇关于控制器中的include_root_in_json的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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