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 ?
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With