strong parameter and json input rails 4

10,642

You could try changing your referral_params method to this:

def referral_params
  json_params = ActionController::Parameters.new( JSON.parse(request.body.read) )
  return json_params.require(:person).permit(:id, user_attributes: [:id, :first_name, :last_name, :email], device_attributes: [:id, :os_type, :os_version], location_attributes: [:id, :latitude, :longitude], duration_attributes[:id, :start_time, :end_time])
end

The first line inside the method parses your JSON (which returns a Ruby hash, if I remember correctly) and creates a new ActionController::Parameters object from that. The second one uses permit and require on that params-like object.

params is usually automatically created from post data key/value pairs, and will be of the type ActionController::Parameters. To use permit and require, you have to create an object of that class manually from a hash.


To then use these sanitized params, you have to change

@inputData = Person.new(JSON.parse(data))

to

@inputData = Person.new(referral_params)
Share:
10,642
JNI_OnLoad
Author by

JNI_OnLoad

Embedded Linux, shell scripting, Yocto Build environment, programming in various languages.

Updated on July 20, 2022

Comments

  • JNI_OnLoad
    JNI_OnLoad almost 2 years

    I am trying to save data through JSON String in which I have nested associated attributes. I do not want to use attr_accessible. I almost got the logic of strong parameter but still got the problem to make them work. I am getting JSON string and using it to save data using this

    data = request.body.read
    @inputData = Person.new(JSON.parse(data))
    @inputData.save!
    [email protected]?
      render :status => 200, :json => "Data inserted successfully"
    else
      render :status => 404, :json => "Not Inserted "
    end
    

    I have defined permit strong parameter method allow nested attributes like this

    def referral_params
    params.require(:person).permit(:id, user_attributes: [:id, :first_name, :last_name, :email], device_attributes: [:id, :os_type, :os_version], location_attributes: [:id, :latitude, :longitude], duration_attributes[:id, :start_time, :end_time]) end
    

    But I am not sure how to use this regerral_params method along with JSON input string....

  • JNI_OnLoad
    JNI_OnLoad about 10 years
    Thanks for the answer, it seems like it now working...just need to test it well