遍历rails 4中的嵌套参数

时间:2015-04-17 10:49:45

标签: ruby-on-rails ruby ruby-on-rails-3 ruby-on-rails-4 nested-forms

有没有办法遍历rails中的参数? 我有一个嵌套的参数:

"request"=>{"name"=>"Gianni Hayes",
   "address"=>"5858 Bernhard Burgs",
   "phone"=>"(972) 399-9601",
   "mobile"=>"777 777 01 02",
   "filled_cartridges_attributes"=>{
      "0"=>{
         "cartridge_id"=>"HP laserjet 300",
         "_destroy"=>"false"}
          },
 "description"=>"sakld",
 "responsible"=>"15",

可能有很多“filled_cartridges_attributes,所以我需要在控制器中迭代它们。

3 个答案:

答案 0 :(得分:0)

因为params基本上是一个哈希。您可以使用Hash#each

params = "request"=>{"name"=>"Gianni Hayes",
   "address"=>"5858 Bernhard Burgs",
   "phone"=>"(972) 399-9601",
   "mobile"=>"777 777 01 02",
   "filled_cartridges_attributes"=>{
      "0"=>{
         "cartridge_id"=>"HP laserjet 300",
         "_destroy"=>"false"}
          },
 "description"=>"sakld",
 "responsible"=>"15"}
}
params["request"].each { |key, value| puts key.to_s + " : " + value.to_s }
# name : Gianni Hayes
# address : 5858 Bernhard Burgs
# phone : (972) 399-9601
# mobile : 777 777 01 02
# filled_cartridges_attributes : {"0"=>{"cartridge_id"=>"HP laserjet 300", "_destroy"=>"false"}}
# description : sakld
# responsible : 15

或者以散列的哈希值递归地执行:

 def deep_traverse(hash)
    hash.each do |key, val|
       puts key
       if val.is_a?(Hash)
         display val
       else
         puts val
       end
    end
 end
 deep_traverse params
 # request
 # Gianni Hayes
 # 5858 Bernhard Burgs
 # (972) 399-9601
 # 777 777 01 02
 # HP laserjet 300
 # false
 # sakld
 # 15

答案 1 :(得分:0)

简单地说,就像哈希一样。如果您有以下哈希:

response = {"request"=>{"name"=>"Gianni Hayes",
                       "address"=>"5858 Bernhard Burgs",
                        "phone"=>"(972) 399-9601",
                        "mobile"=>"777 777 01 02",
                        "filled_cartridges_attributes"=>{
                              "0"=>{
                              "cartridge_id"=>"HP laserjet 300",
                              "_destroy"=>"false"}
                         },
                         "description"=>"sakld",
                         "responsible"=>"15"}
                       }
           }

现在,这是访问filled_cartridges_attributes的方法:

response["request"]["filled_cartridges_attributes"].each do |_, value|
  puts value["cartridge_id"] # => HP laserjet 300"
  ...
  ...
end

答案 2 :(得分:0)

params[:request][:filled_cartridges_attributes]会返回一个哈希值,因此您可以使用eacheach_valueeach_key对其进行迭代 像:

params[:request][:filled_cartridges_attributes].each_value {|value| p value}