Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 3 params unwanted wrapping

Tags:

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 ?

like image 840
Blacksad Avatar asked Feb 03 '12 18:02

Blacksad


1 Answers

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.

like image 141
Rob Davis Avatar answered Jan 31 '23 06:01

Rob Davis