如何循环控制器中的一些嵌套参数? Rails 3

时间:2012-08-09 17:00:55

标签: ruby-on-rails ruby-on-rails-3 controller params

我有一个'run'对象,可以在其中保存许多'层'。运行接受图层的嵌套属性,但是在发生各种不良事件之前,rails无法确保嵌套对象的参数有效。我正在尝试检查任何层上的'deposition_source_id'参数是否为空。如何循环图层?
该行可以从一个层或任何层获取参数。 “0”指定图层 params[:run][:layers_attributes]["0"][:deposition_source_id]

如何检查每一层?这些是参数:

    => {"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"}

1 个答案:

答案 0 :(得分:6)

你可以这样做:

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

如果您只想确保deposit_source_id始终为空,我会这样做:

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