Rails 3 params 不需要的包装 [英] Rails 3 params unwanted wrapping

查看:25
本文介绍了Rails 3 params 不需要的包装的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在发布一些 JSON,例如 {:name => 的 JSON 形式.你好"} 到我的 Rails 3 控制器 ExampleController.

I'm posting some JSON like the JSON form of {:name => "hello"} to my Rails 3 controller ExampleController.

而不是像这样获取params:

{:name => "hello"}

我得到:

{:name => "hello", :controller => "example", :action => "index", :example => {:name => "hello"}

(是的,JSON 数据出现了两次!并添加了动作和控制器)

(Yes the JSON data appears twice! and action and controller are added)

知道为什么吗?

推荐答案

ActionController 自动为 JSON 请求执行此操作,以便您可以轻松地将参数传递到 Example.create@example.update_attributes,这意味着客户端不需要为您的模型打包它们——它可以只包含 name 等.阿尔.在 JSON 数据的顶层,控制器将处理分组.

ActionController automatically does this for JSON requests so that you can easily pass the parameters into Example.create or @example.update_attributes, which means the client doesn't need to package them up for your model -- it can just include name et. al. at the top level of your JSON data and the controller will handle the grouping.

@example = Example.create params[:example]

参数包装代码从控制器的名称中获取模型的名称,但您可以使用 wrap_parameters 控制器中的宏:

The parameter wrapping code gets the name of your model from the name of the controller, but you can change it using the wrap_parameters macro in your controller:

wrap_parameters :thing

或者用

wrap_parameters false

在 Rails 3.2 中,如果您的模型使用 attr_accessible,则参数包装功能还将排除无法进行批量分配的任何参数.如果您愿意,您还可以使用该宏将此包装功能应用于除 JSON 之外的其他内容类型.

In Rails 3.2, if your model uses attr_accessible, the parameter wrapping feature will also exclude any parameters that are not accessible to mass assignment. You can also use the macro to make this wrapping feature apply to other content types besides JSON, if you like.

默认情况下,在新创建的 Rails 应用程序中,这是为使用初始化程序的所有控制器配置的.查找 config/initializers/wrap_parameters.rb.

By default in a newly created Rails app, this is configured for all controllers using an initializer. Look for config/initializers/wrap_parameters.rb.

这篇关于Rails 3 params 不需要的包装的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆