Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails wrap_parameters vs include_root_in_json, what is the difference?

In a new Rails 3.2 app you can find in config/initializers/wrap_parameters.rb the following lines:

ActiveSupport.on_load(:action_controller) do   wrap_parameters format: [:json] end  # Disable root element in JSON by default. ActiveSupport.on_load(:active_record) do   self.include_root_in_json = false end 

My understanding for the second code block is that if you convert a object to json, it will not include a root node (i.e. users => {:name => 'John'}, rather it will be just {:name => 'john'}

What then does the first wrap_parameters block do? It acts on action_controller.. why?

like image 552
Inc1982 Avatar asked May 27 '12 15:05

Inc1982


1 Answers

include_root_in_json is to wrap json instantiated in Rails

wrap_parameters is to wrap json received from a request.

If you have wrap_parameters enabled, and if you send the following json through a POST command to Rails:

{name: 'John Smith'}

Rails will automatically wrap the JSON it received into:

{"person": {name: 'John Smith'}}

include_root_in_json, on the other hand, is whether the json Rails generates from an object is wrapped or not through the to_json command.


e.g. Person.to_json. If include_root_in_json is enabled, you'll get:

{"person": {name: 'James Brown'}}

Otherwise, you'll just get

{name: 'John Smith'}

like image 189
jstrong Avatar answered Sep 21 '22 22:09

jstrong