将Parameters或HashWithIndifferentAccess中的值转换为可用的哈希

时间:2015-10-21 00:02:16

标签: ruby-on-rails hash parameters haml rails-activerecord

当值包含哈希值时,我很难找到一种从参数哈希或对哈希无差别访问的哈希转换的方法。

我无法转换此内容:

hash_indif = {"1570"=>"{:enabled=>false}",
              "1571"=>"{:enabled=>false}",
              "1572"=>"{:enabled=>false}",
              "1573"=>"{:enabled=>false}",
              "1574"=>"{:enabled=>false}",
              "1575"=>"{:enabled=>false}",
              "1576"=>"{:enabled=>false}",
              "1577"=>"{:enabled=>false}",
              "1578"=>"{:enabled=>false}"}

对此:

hash_thing = {1570 => {:enabled => false},
              1571 => {:enabled => false},
              1572 => {:enabled => false},
              1573 => {:enabled => false},
              1574 => {:enabled => false},
              1575 => {:enabled => false},
              1576 => {:enabled => false},
              1577 => {:enabled => false},
              1578 => {:enabled => false}}

如果可能的话,我希望能够使用方法链接。

其他信息

这种情况是由于尝试从同一个密钥更新多个属性而导致的。

Haml的:

- @a_feature.each do |af|
  .form-inline.radio-group
    %label= af.feature.name
    =radio_button "a_feature", af.id, [enabled: true], {checked: af.enabled, class:'form-control'}
    %label Yes
    =radio_button "a_feature", af.id, [enabled: false], {checked: !af.enabled, class:'form-control'}
    %label No

参数:

 {"utf8"=>"✓",
 "_method"=>"patch",
 "a_feature"=>{
 "296"=>"{:enabled=>true}",
 "344"=>"{:enabled=>false}",
 "376"=>"{:enabled=>false}",
 "commit"=>"Save",
 "agency_id"=>"7"}

1 个答案:

答案 0 :(得分:1)

这是一个不使用eval的快速​​解决方法

def to_bool(str)
    str == 'true'
end

new_hash = Hash.new
hash_indif.each do |i, j|
    inner_hash = Hash.new
    match_data = /^{:(enabled)=>(false|true)}$/.match(j)
    inner_hash[match_data[1].intern] = to_bool match_data[2]
    new_hash[i.to_i] = inner_hash
end

new_hash变量包含您需要的输出 -

{1570=>{:enabled=>false}, 1571=>{:enabled=>false}, 1572=>{:enabled=>false}, 1573=>{:enabled=>false}, 1574=>{:enabled=>false}, 1575=>{:enabled=>false}, 1576=>{:enabled=>false}, 1577=>{:enabled=>false}, 1578=>{:enabled=>false}}