问题描述
在一个新的 Rails 3.2 应用程序中,您可以在 config/initializers/wrap_parameters.rb 中找到以下几行:
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
我对第二个代码块的理解是,如果您将对象转换为 json,它将不包含根节点(即用户 => {:name => 'John'},而只是 {:name=> '约翰'}
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'}
那么第一个 wrap_parameters 块做了什么?它作用于 action_controller.. 为什么?
What then does the first wrap_parameters block do? It acts on action_controller.. why?
推荐答案
include_root_in_json
是在 Rails 中包装 json 实例化
include_root_in_json
is to wrap json instantiated in Rails
wrap_parameters
是对从请求中接收到的 json 进行包装.
wrap_parameters
is to wrap json received from a request.
如果您启用了 wrap_parameters
,并且您通过 POST 命令将以下 json 发送到 Rails:
If you have wrap_parameters
enabled, and if you send the following json through a POST command to Rails:
{name: 'John Smith'}
Rails 会自动将它收到的 JSON 包装成:
Rails will automatically wrap the JSON it received into:
{"person": {name: 'John Smith'}}
include_root_in_json
,另一方面,是 json Rails 生成 对象是否通过 to_json
命令包装.
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.
例如Person.to_json
.如果启用 include_root_in_json
,您将获得:
e.g. Person.to_json
. If include_root_in_json
is enabled, you'll get:
{"person": {name: 'James Brown'}}
否则,你只会得到
{name: 'John Smith'}
这篇关于Rails wrap_parameters vs include_root_in_json,有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!