2010-02-17 35 views
0

我有哈希散列像這樣:搜索與紅寶石一蘇巴on Rails的

Parameters: {"order"=>{"items_attributes"=>{"0"=>{"product_name"=>"FOOBAR"}}}} 

鑑於深度和按鍵的名稱可能會改變,我需要能夠提取的'價值product_name'(在這個例子中是「FOOBAR」),但是我似乎無法弄清楚。

還有個問題是,params爲(我認爲)一個HashWithIndifferentAccess

感謝您的幫助。

回答

0

這是你的意思嗎?

if params.has_key?("order") and params["order"].has_key?("items_attributes") then 
    o = params["order"]["items_attributes"] 
    o.each do |k, v| 
     # k is the key of this inner hash, ie "0" in your example 
     if v.has_key?("product_name") then 
      # Obviously you'll want to stuff this in an array or something, not print it 
      print v["product_name"] 
     end 
    end 
end 
+0

感謝您的回覆,但我不認爲如果關鍵'product_name'是更深一些的子集,這個解決方案將無法正常工作。 – doctororange