来自控制器的include_root_in_json

ped*_*ete 9 json ruby-on-rails

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

我不想在此模型的所有操作上设置此项,因此我尝试避免设置

ActiveRecord.Base.include_root_in_json = false

我希望我能做到

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

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

有一个很好的方法吗?

rch*_*ier 12

现在这是一个老问题,但答案没有更新,Rails 3.2填补了空白(Rails源代码)

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

my_model.to_json(:root => false)
Run Code Online (Sandbox Code Playgroud)

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

我刚刚用数组测试它会变得更好,所以你可以这样做:

Model.all.to_json(:root => true)
Run Code Online (Sandbox Code Playgroud)


Jim*_*dra 5

从查看ActiveModel :: Serializers :: JSON#as_json的源代码来看,似乎没有办法include_root_in_json在每个方法调用的基础上更改值.除非我遗漏了某些内容,否则最好的办法是在通话之前更改类变量,然后再将其更改为:

ActiveRecord::Base.include_root_in_json = false
render :json => @task
ActiveRecord::Base.include_root_in_json = true
Run Code Online (Sandbox Code Playgroud)

这非常难看,但似乎"在json中包含root"选项并没有考虑到这种灵活性.它也可能导致其他请求的竞争条件,但我不确定.或者,您可以始终将其设置为false,并在需要的情况下手动创建带有根密钥的哈希:

# this case
render :json => @task

# some other case
render :json => { :my_model => @my_model.to_json }
Run Code Online (Sandbox Code Playgroud)