Karthikds
Karthikds

Reputation: 247

access the nested attributes

This is my params hash. I just want to get each name and email_id and want to process further on those. Pls tell me how can I get this. Help me out since I am new to 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"
}

Upvotes: 2

Views: 403

Answers (1)

jvnill
jvnill

Reputation: 29599

here's one way of doing it using a recursive function

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

Upvotes: 1

Related Questions