如何正确迭代参数

时间:2012-03-01 17:15:41

标签: ruby-on-rails ruby ruby-on-rails-3 hash

如何在控制器中循环使用params以便我可以更改它们的值?

此:

...
params[:contact][:relationships_attributes].each do |rel|
  rel[:contact_ids] = [rel[:contact_ids]]
end
...

返回错误:

# can't convert Symbol into Integer

为了提供更多上下文,我使用单个选择框代替多选。所以控制器期待一个数组,而不是它获得一个值。

这是我的参数:

{"utf8"=>"✓",
"_method"=>"put",
"authenticity_token"=>"8FrW59t9vzSep+jEGceMdE/b5q69i5hrEp08yZJJk0o=",
"contact"=>
  {"first_name"=>"John",
   "last_name"=>"Smith",
   "email_addresses_attributes"=>
    {"0"=>
      {"value"=>"john.smith@gmail.com",
       "type"=>"Home",
       "_destroy"=>"false",
       "id"=>"4f4eea6dbe5a2ccf03000031"
      },
       "1"=>{"value"=>"john@smith.com",
       "type"=>"Home",
       "_destroy"=>"false",
       "id"=>"4f4eea7dbe5a2ccf03000035"
      }
    },
  "phone_numbers_attributes"=>
    {"0"=>
      {"value"=>"555-334-5959",
       "type"=>"Home",
       "_destroy"=>"false",
       "id"=>"4f4eea64be5a2ccf0300002c"}
    },
  "addresses_attributes"=>
    {"0"=>
      {"type"=>"Home",
       "street_address"=>"12345 Any Rd",
       "city"=>"Anytown",
       "state"=>"CO",
       "country"=>"United States",
       "_destroy"=>"false",
       "id"=>"4f4eea64be5a2ccf0300002d"
      }
    },
  "relationships_attributes"=>
    {"1330623965418"=>
      {"contact_ids"=>"4f4e6696be5a2ca2a7000045",
       "title"=>"Wife",
       "_destroy"=>"false"
      }
    }
  },
  "commit"=>"Update Contact",
  "id"=>"4f4e6696be5a2ca2a7000045"
}

1 个答案:

答案 0 :(得分:18)

在像这样的哈希上使用each

params[:contact][:relationships_attributes].each do |rel|

块参数rel实际上是一个双元素数组,其中键位于0位,值位于位置1.然后您的块尝试访问数组,就好像它是一个哈希:

rel[:contact_ids]

并解释了您的错误消息:您无法使用符号索引数组。

我想你想做更像这样的事情:

params['contact']['relationships_attributes'].each do |k, v|
  v['contact_ids'] = [ v['contact_ids'] ] unless v['contact_ids'].is_a?(Array)
end

这会给你一个像这样的结构:

{
  :contact => {
    :relationships_attributes => {
      '1330623965418' => {
        :contact_ids => ['4f4e6696be5a2ca2a7000045']
        :title => 'Wife',
        :_destroy => 'false'
      }
      ...