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?
Read up the documentation on Rails
to_jsonhere.So adding to your environment/application.rb
should solve your issues.