Steffen Witvliet
Steffen Witvliet

Reputation: 3

How can i get values out when i've got a hash of hashes?

I am getting the following code in my params (send from a simple form in haml with a simple_field_for block. All the data I needed is in here but I'm having trouble getting it out the way I wanted.

my params:

"report_templates"=>{"1"=>{"start_year"=>"2015", "start_period"=>"", "use_concept_data"=>"0", "name"=>"Financieel jaaroverzicht", "id"=>"1"},    "3"=>{"start_year"=>"2015", "start_period"=>"", "use_concept_data"=>"0", "name"=>"Klanten", "id"=>"3"}}

I have report_templates with settings for each report template. now in the controller I want to use these setting to render a .pdf report for each template.

what I need is:

"1"=>{"start_year"=>"2015", "start_period"=>"", "use_concept_data"=>"0", "name"=>"Financieel jaaroverzicht", "id"=>"1"}

I now I can access the settings by doing

params[:report_template]["1"] 

and getting this back

{"start_year"=>"2015", "start_period"=>"", "use_concept_data"=>"0", "name"=>"Financieel jaaroverzicht", "id"=>"1"}

But I want to do it dynamic in my controller. because the id of the report_template can be any number.

my controller:

report_settings = params[:report_templates]
report_settings.each do |rs|
 rs[:id]

But I am not getting the id from each template..

I hope someone can help me solving my problem.

Upvotes: 0

Views: 42

Answers (1)

Arup Rakshit
Arup Rakshit

Reputation: 118299

So, you were close. But little more work need to be done.

report_settings = params[:report_templates]
report_settings.each do |report_id, report_value|
  # now you have access to the key(report_id) 
  # and value(report_value) both
end

If you don't need key, but only values, then :

report_settings = params[:report_templates]
report_settings.each do |_, report_value|
  # now you have access the value(report_value)
end

Read Hash#each method for detail documentation.

Upvotes: 1

Related Questions