mercredi 12 octobre 2022

How to validate presence of attributes in json objects in an array in rails 3?

I am supposed to create an API for storing record that comes from json object. Basically the Json object contains an array of json objects that need to be validated before saving to db. e.g

    { 
      "request": [ 
                {
                 "country_id": 123,
                 "state_id" : 43,
                 "active": true,
                },
                {
                 "country_id": 234,
                 "state_id": 56,
                 "active": false,
                }
               ]
       }

So these objects needs to be inserted in Profile model in bulk which has country_id, state_id and active as attributes. So I want to validate the presence of attributes in the JSON objects in the Array while looping through them. If gets validated insert in the db otherwise return validation error in response.

    array = params[:request]
    array.each do |obj|
       Profile.new(obj)
       Profile.save!
    end
                  
           

Aucun commentaire:

Enregistrer un commentaire