From 50639c97eb326a16f35f94e56e57aff4a4985003 Mon Sep 17 00:00:00 2001 From: Prem Sichanugrist Date: Fri, 13 May 2011 14:31:09 -0400 Subject: Adding guide for wrapping JSON/XML parameters, which also links to the API documentation. Note that it currently links to http://edgeapi.rubyonrails.org because it's Rails 3.1 feature. --- .../source/action_controller_overview.textile | 26 ++++++++++++++++++++++ 1 file changed, 26 insertions(+) (limited to 'railties/guides/source/action_controller_overview.textile') diff --git a/railties/guides/source/action_controller_overview.textile b/railties/guides/source/action_controller_overview.textile index 3a1a4ee66e..7ace6e6fdc 100644 --- a/railties/guides/source/action_controller_overview.textile +++ b/railties/guides/source/action_controller_overview.textile @@ -110,6 +110,32 @@ When this form is submitted, the value of +params[:client]+ will be {"name" Note that the +params+ hash is actually an instance of +HashWithIndifferentAccess+ from Active Support, which acts like a hash that lets you use symbols and strings interchangeably as keys. +h4. JSON/XML parameters + +If you're writing a web service application, you might find yourself more comfortable on accepting parameters in JSON or XML format. Rails will automatically convert your parameters into +params+ hash, which you'll be able to access it like you would normally do with form data. + +So for example, if you sending this JSON parameter: + +
+{ "company": { "name": "acme", "address": "123 Carrot Street" }}
+
+ +You'll get +params[:company]+ as +{ :name => "acme", "address" => "123 Carrot Street" }+. + +Also, if you've turned on +config.wrap_parameters+ in your initializer or calling +wrap_parameters+ in your controller, you can safely omit the root element in the JSON/XML parameter. The parameters will be cloned and wrapped in the key according to your controller's name by default. So the above parameter can be written as: + +
+{ "name": "acme", "address": "123 Carrot Street" }
+
+ +And assume that you're sending the data to +CompaniesController+, it would then be wrapped in +:company+ key like this: + + +{ :name => "acme", :address => "123 Carrot Street", :company => { :name => "acme", :address => "123 Carrot Street" }} + + +You can customize the name of the key or specific parameters you want to wrap by consulting the "API documentation":http://edgeapi.rubyonrails.org/classes/ActionController/ParamsWrapper.html" + h4. Routing Parameters The +params+ hash will always contain the +:controller+ and +:action+ keys, but you should use the methods +controller_name+ and +action_name+ instead to access these values. Any other parameters defined by the routing, such as +:id+ will also be available. As an example, consider a listing of clients where the list can show either active or inactive clients. We can add a route which captures the +:status+ parameter in a "pretty" URL: -- cgit v1.2.3