Marcos Icaza Marcos Icaza - 2 months ago 9
Ruby Question

Ruby On Rails: how to extract nested parameters from POST request

I want to grab the values for the keys

id
and
quantity
from the
params
hash submitted with a POST form.

The parameters:

params
# => {...
"form"=>
{"name"=>"joe",
"date_sent"=>"09/28/2016",
"emp_num"=>"54552452",
"items_attributes"=>{"1474227471986"=>{"id"=>"3", "quantity"=>"5", "_destroy"=>"false"}, "1474227474062"=>{"id"=>"4", "quantity"=>"3", "_destroy"=>"false"}},
"comments"=>"af",
"accepted"=>"false"},
"commit"=>"Submit",
"m"=>"true"}

Answer

In following way you can grab id and quantity of all nested item attributes.

params['form']['items_attributes'].values.collect { |value| { id: value['id'], quantity: value['quantity'] } }

Output:

[ {:id => 3, :quantity => 5 }, { :id => 4, :quantity => 3 } ]