How do I iterate over some nested parameters in the controller? Rails 3

I have a "run" object that can contain many "layers" inside it. Runs accepts nested attributes for layers, but the rails cannot make sure that the parameters of the nested object are valid before all kinds of bad things happen. I am trying to check if the parameter "depositition_source_id" is empty on any of the layers. How can I go through the layers?
This line can receive parameters from ONE or any of the layers. "0" indicates the layer.
params[:run][:layers_attributes]["0"][:deposition_source_id]

How can I check each layer? These are the options:

  => {"utf8"=>"✓", "_method"=>"put", "authenticity_token"=>"T+X6sSda5vV19hpMZEAdf5RWSKPhJrm/q9+NXxTC5G8=", "run"=> {"number"=>"31310.0", "start_time_string"=>"08/08/2012 at 11:08 AM", "system_id"=>"4", "technician_id"=>"4", "duration"=>"", "base_pressure"=>"", "platters"=>"Apples", "overcoats_string"=>"", "planetary"=>"", "layers_attributes"=> {"0"=> {"deposition_source_id"=>"", "material_id"=>"60", "lot_id"=>"118", "thickness_goal"=>"32", "measured_thickness"=>"3", "tooling_factor"=>"", "sensor_number"=>"", "xtal_life"=>"", "release_agent"=>"0", "_destroy"=>"false", "id"=>"3401"}}}, "commit"=>"Update Run", "action"=>"update", "controller"=>"runs", "id"=>"2319"} 
+4
source share
1 answer

You can do something like this:

 params[:run][:layers_attributes].each do |layer_number, params| # do your validation here on params[:deposition_source_id] end 

If all you want to do is make sure depositition_source_id is always empty, I would do it like this:

 deposition_source_id_is_empty = true params[:run][:layers_attributes].each do |layer_number, params| if params[:deposition_source_id].present? deposition_source_id_is_empty = false break end end if deposition_source_id_is_empty # do the things you'd do here if the parameters pass validation end 
+6
source

All Articles