views:

32

answers:

1

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.

A: 

I did not find a way to do this by passing options to the to_json method (and I don't believe there is such an option). You have more alternative to do this, any class that inherits from ActiveRecord::Base will have include_root_in_json.

Do something like this.

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

Hope this gets you going.

Ok let's try this then.

DataController < ApplicationControlle

  private

  def custom_json(data)
    Data.include_root_in_json = false
    data.to_json
    Data.include_root_in_json = true
    data
  end
end

Then your redirect would look like this

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

It's pretty silly code I wish I could think of something else entirely. Let me ask you this: What is it about having the model name included in the json data ?

Hugo
I just tried this, and it has the effect of changing include_root_in_json to false globally, unfortunately. I'm running Rails 2.3.5, if that helps.
CCSab