Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails rendering JSON data with Model Root

I've got some data in Rails that I want to render as JSON data. What I'm doing right now is simply finding all instances of a Model and calling render :json=>data.

data = Data.find(:all)
render :json => data

However, Rails is including the model name in each JSON object. So my JSON data ends up looking like this:

[{modelname:{propertyName: 'value',...}},{modelname:{propertyName: 'value2',...}}]

instead of this: [{propertyName:'value',...},{propertyName:'value2',...}]

The modelname is always the same and I don't want it to be there.

I changed the option to render the root in the JSON data in one of the Rails initializers but that affects everything that I want rendered as JSON, which I don't want to do for this project.

In this case, I want to be able to do this on a case-by-case basis.

How can I do this? Thanks in advance.

like image 450
CCSab Avatar asked Aug 26 '10 16:08

CCSab


1 Answers

With Rails 3, you can use active_model_serializers gem1

that allows you to specify rootless rendering of an object like this:

render :json => data, :root => false
like image 62
Vladimir Ivanov Avatar answered Oct 20 '22 07:10

Vladimir Ivanov