Ram Laxman Yadav bio photo

Ram Laxman Yadav

Ruby on Rails Developer

Email Twitter LinkedIn Github Stackoverflow

Hello Friends, Generally we request a root element in request params, from a rest api. Suppose if you have a REST api for create user with name then you have to give data in format like: {"user": {"name": "somename"}}. Here a root element user is required. What if you want to post data without root element, Here the wrapping concept comes. Here is on example of that

What is ParamsWrapper

ParamsWrapper is available inside ActionController::ParamsWrapper . It wraps the parameters hash into nested hash. It allow clients to submit requests without having a specific root element.

How to use

This functionality is enabled in config/initializers/wrap_parameters.rb and can be customized. By default it is enable for :json format but you can customize it for other formats as well.

class BulletinsController < ApplicationController
  wrap_parameters format: [:json, :xml, :url_encoded_form, :multipart_form] #etc
end

Now, instead of having to send JSON parameters like this:

{
    bulletin: {
        name: 'bulletin_name'
    }
 }
  

you can send request with parameter

   {
        name: 'bulletin_name'
    }

It will wrapped params into a nested hash with the key name matching the controller name. In my case it will be like

   {
        name: 'bulletin_name',
        bulletin: {
                   name: 'bulletin_name' 
                   }
    }

You can also :include and :exclude parameters. As like:

class BulletinsController < ApplicationController
  wrap_parameters :bulletin, include: [:name]
end

Thanks for reading for more documentation, Please refer the link