开发者

include_root_in_json from controller

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

I was hoping that I could do

@task = Tasks.all
开发者_Go百科@task.include_root_in_json = false

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??


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

With Rails 3.2, you can now use:

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)


From looking at the source for ActiveModel::Serializers::JSON#as_json, it appears there is not a way to change the value of include_root_in_json on a per-method-call basis. Unless I'm missing something, your best recourse is to change the class variable before your call and change it back afterward:

ActiveRecord::Base.include_root_in_json = false
render :json => @task
ActiveRecord::Base.include_root_in_json = true

This is pretty ugly, but it seems that the "include root in json" option wasn't designed with this level of flexibility in mind. It might also cause a race condition with other requests, but I'm not sure about that. Alternatively, you could always keep it set to false, and manually create a hash with a root key in cases where you need that:

# this case
render :json => @task

# some other case
render :json => { :my_model => @my_model.to_json }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜