msmith1114
msmith1114

Reputation: 3229

Permitting JSON Array Parameters in Rails

Having a bit of trouble, im trying to permit array parameters and i've seen example of that...however I haven't seen an example where the array is an array of objects and the top level array is one of the main params being pulled in.

Sample JSON:

{
  "message_json": {
    "device": {
      "deviceid": "002"
    },
     "measurements": 
        [
            {
          "temp": 71.45,
          "humidity": 31.5
            },
            {
            "temp": 75.34,
            "humidity": 35.9
            }
        ]
  }
}

Functions for permitting:

   def device_params
      params[:message_json].fetch(:device, {}).permit(:deviceid)
   end

   def measurement_params
      params[:message_json].fetch(:measurements, {}).permit(:temp,:humidity)
   end

So the measurement_params does not work, and I know normally you'd do something like array_obj: [] but this arrays object is already the measurements param thats getting fetched? How would I go about permitting these items?

Upvotes: 1

Views: 1594

Answers (1)

Did you try something like this:

def measurement_params
   params.require(:message_json).permit(measurements: [:temp, :humidity])
end

I am unable test this right now. But I was dealt with this problem and solved with this way.

Upvotes: 2

Related Questions