2016-03-10 262 views
0

我有以下嵌套哈希嵌套哈希 - 红宝石

def testy_user 
{ 
    search_templates: { 
    profile_1: { default_search_form: 'simple', name: 'Automation Profile', default_profile: 'yes', profile_set: 'standard', ref_required: 'no', fk_search_type_id: '1' }, 
    profile_2: { default_search_form: '', name: 'Potential Links', default_profile: 'no', profile_set: 'standard', ref_required: 'no', fk_search_type_id: '1' }, 
    profile_3: { default_search_form: '', name: 'Insolvency', default_profile: 'no', profile_set: 'standard', ref_required: 'no', fk_search_type_id: '1' }, 
    profile_4: { default_search_form: '', name: 'Mortality', default_profile: 'no', profile_set: 'standard', ref_required: 'no', fk_search_type_id: '1' }, 
    profile_5: { default_search_form: '', name: 'Mortality', default_profile: 'no', profile_set: 'standard', ref_required: 'no', fk_search_type_id: '1' }, 
    profile_6: { default_search_form: '', name: 'PRS', default_profile: 'no', profile_set: 'standard', ref_required: 'no', fk_search_type_id: '1' }, 
    profile_7: { default_search_form: '', name: 'Neighbour', default_profile: 'no', profile_set: 'standard', ref_required: 'no', fk_search_type_id: '1' }, 
    profile_8: { default_search_form: '', name: 'Smartlinks', default_profile: 'no', profile_set: 'standard', ref_required: 'no', fk_search_type_id: '1' }, 
    profile_9: { default_search_form: '', name: 'Property', default_profile: 'no', profile_set: 'standard', ref_required: 'no', fk_search_type_id: '1' }, 
    profile_10: { default_search_form: '', name: 'Occupants', default_profile: 'no', profile_set: 'standard', ref_required: 'no', fk_search_type_id: '1' } 
    } 
} 
end 

我放在一起的一些逻辑,将通过每一个“轮廓”迭代并写信给我的数据库(使用MySQL宝石)

testy_user[:search_templates].select { |p| p=[/^profile_/] }.each do |template| 
    statement = @db.prepare('INSERT INTO profile (fk_user_id, default_search_form, name, default_profile, ref_required, fk_search_type_id) VALUES(?,?,?,?,?,?)') 
    statement.execute(@user_id, template[:default_search_form], template[:name], template[:default_profile], template[:ref_required], template[:fk_search_type_id]) 
end 

因为我现在在这个循环中,每个template是一个数组,我不能再作为符号访问键(我得到TypeError:没有将符号隐式转换为整数)

我需要转换把数组中的每一项都放回到哈希中,还是有更接近这个的更清晰的方法?

感谢

回答

2

你,你所面临的问题的假设是不相关的实际问题。

select条件有误(它甚至没有条件,它是一个赋值)。此外,应明确地定义,其中是键(key),并且其中对应于它元件(_ - 强调装置,您没有在块的上下文使用的话):

testy_user[:search_templates].select{|key, _| key =~ /^profile_/ }.each do |_, template| 
    <your code> 
end 
+0

道歉,错字意味着我错过了我的'testy_user方法'花括号 – Richlewis

+1

谢谢你的帮助和澄清我的错误 – Richlewis