Rails wrap_parameters vs include_root_in_json, wha

2020-02-08 04:01发布

问题:

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?

回答1:

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'}