Rails 3 params unwanted wrapping

徘徊边缘 提交于 2019-12-28 11:53:53

问题


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

Instead of getting params like:

{:name => "hello"}

I'm getting:

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

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

Any idea why ?


回答1:


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]

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

Or turn it off with

wrap_parameters false

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.

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



来源:https://stackoverflow.com/questions/9133652/rails-3-params-unwanted-wrapping

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!