JSON serialization on Ruby on Rails

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

I am returning a JSON object from a controller method (say, the class name is "foo" and has the property "bar").

I expected this to serialize as:

{"bar" : "barValue" }

However, it seems to serialize as

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

This seems incompatible with.) What other languages ​​do, b.) (More importantly) what javascript does.

Let's say I defined the same class foo in Javascript:

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

And then I build using one of the Javascript JSON libraries (for example, https://github.com/douglascrockford/JSON-js ). Then the output is something like lines:

{"bar" : "barValue" }

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

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

Therefore, I need to write code along these lines in order for it to work:

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

, Rails? , ?

+3
1

Rails to_json .

ActiveRecord:: Base.include_root_in_json to_json. Rails, true /new _rails_defaults.rb. , to_json node, .

, /application.rb

config.active_record.include_root_in_json = true

.

+9

Source: https://habr.com/ru/post/1795102/