tgallard
tgallard

Reputation: 401

Ruby on Rails JSON serialization

I'm a complete newcomer to Ruby on Rails so please forgive me if this is an obvious question.

I'm returning a JSON object from a controller method (let's say the class name is "foo" and it has a property "bar").

I'd expected this to serialize as:

{"bar" : "barValue" }

However, it seems to serialize as

{"foo" : {"bar" : "barValue"}}

This seems out of joint with a.) what other languages do , b.) (More importantly) what javascript does.

Say I've defined the same class foo in Javascript:

var fooInstance = new Foo();
fooInstance.bar = "barValue";

And I then stringify that using one of a Javascript JSON library (e.g. https://github.com/douglascrockford/JSON-js ). Then the output is something along the lines of:

{"bar" : "barValue" }

But inputs (as well as outputs) to my controller methods expect:

{"foo" : {"bar" : "barValue"}

So I have to write code along these lines to make it work:

var fooInstance = new Foo();
fooInstance.bar = "barValue";
var dummyObjectToKeepRailsHappy = { foo : fooInstance};

So- am I doing Rails serialization incorrectly? Or is there a reason it works this way?

Upvotes: 3

Views: 3003

Answers (1)

Marcel Jackwerth
Marcel Jackwerth

Reputation: 54782

Read up the documentation on Rails to_json here.

The option ActiveRecord::Base.include_root_in_json controls the top-level behavior of to_json. In a new Rails application, it is set to true in initializers/new_rails_defaults.rb. When it is true, to_json will emit a single root node named after the object’s type.

So adding to your environment/application.rb

config.active_record.include_root_in_json = true

should solve your issues.

Upvotes: 9

Related Questions