myhouse
myhouse

Reputation: 1991

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"}

Upvotes: 1

Views: 567

Answers (1)

Aamir
Aamir

Reputation: 16957

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 } ]

Upvotes: 1

Related Questions