2013-02-01 187 views
2

這是我的params散列。我只想獲得每個姓名和email_id,並且想要對這些進一步處理。請告訴我如何得到這個。自從我剛接觸rails以來幫助我。訪問嵌套屬性

{ 
    "utf8"=>"✓", 
    "_method"=>"put", 
    "authenticity_token"=>"VBJ7NrYDzftlVMYdfNewxADAEGWE8ctau4Zpx3JcjbQ=", 
    "game_school"=>{ 
      "game_school_invites_attributes"=>{ 
       "name"=>"AAA", 
       "email"=>"[email protected]", 
       "1359712354138"=>{ 
        "name"=>"ABCD", 
        "email"=>"[email protected]" 
       }, 
       "1359712366842"=>{ 
        "name"=>"CC", 
        "email"=>"[email protected]" 
       } 
      } 
    }, 
    "commit"=>"invite", 
    "model1_id"=>"5", 
    "model2_id"=>"4" 
} 
+1

做的一種方式似乎是在你的哈希一些問題。在'game_school_invites_attributes'中,您有**名稱** **電子郵件**和** 13597112354138 **等。它應遵循相同的結構。 **名稱**和**電子郵件**應嵌套在另一個索引下,如另一種情況。也許你可以在這裏顯示你的視圖代碼來解析結構。 –

回答

1

這裏是一個使用遞歸函數

def return_name_and_email(hash) 
    if hash['name'] && hash['email'] 
    puts "Name: #{hash['name']}" 
    puts "Email: #{hash['email']}" 
    end 

    hash.keys.each do |key| 
    return_name_and_email(hash[key]) if hash[key].is_a?(Hash) 
    end 
end 

return_name_and_email params