Ruby On Rails:如何从POST请求中提取嵌套参数

时间:2016-09-18 19:52:33

标签: ruby-on-rails ruby ruby-on-rails-4

我想从POST表单提交的id哈希值中获取密钥quantityparams的值。

参数:

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

1 个答案:

答案 0 :(得分:1)

通过以下方式,您可以获取所有嵌套项属性的 ID 数量

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

输出:

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