Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 501
pedalpete Avatar asked Feb 23 '11 21:02

pedalpete


2 Answers

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)
like image 123
Romain Champourlier Avatar answered Nov 08 '22 22:11

Romain Champourlier


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 }
like image 5
Jimmy Avatar answered Nov 08 '22 22:11

Jimmy