postgres,如何将表的所有内容放入哈希?

时间:2018-03-21 17:21:01

标签: ruby postgresql

我想把select中的所有结果都放到一个哈希中,这个哈希会将表的名称作为键,而值是一个包含行的数组,这是我到目前为止所做的: / p>

def table_content_to_hash(table)
 hash = {}
 rs = @pg_conn.exec "SELECT * FROM #{table}";
 rs.each do |child|
  # want to put table name as key and value is an array that has the rows
  hash['#{table}'] = child  # THIS ONE IS WRONG
 end
 puts hash
end

更新,我的代码在使用Spickermann解决方案后工作,结果如下:

{"company"=>[{"id"=>"1", "name"=>"Paul", "age"=>"32", "address"=>"California                                        ", "salary"=>"20000"}, {"id"=>"2", "name"=>"Allen", "age"=>"25", "address"=>"Texas                                             ", "salary"=>"15000"}, {"id"=>"3", "name"=>"Teddy", "age"=>"23", "address"=>"Norway
                                    ", "salary"=>"20000"}, {"id"=>"4", "name"=>"Mark", "age"=>"25", "address"=>"Rich-Mond
", "salary"=>"65000"}, {"id"=>"5", "name"=>"David", "age"=>"27", 
"address"=>"Texas                                             ", 
 "salary"=>"85000"}, {"id"=>"6", "name"=>"Kim", "age"=>"22", 
 "address"=>"South-Hall                                        ", 
 "salary"=>"45000"}, {"id"=>"7", "name"=>"James", "age"=>"24", 
  "address"=>"Houston                                           ", 
"salary"=>"10000"}]}

我不知道如何删除该空间的地址值。 谢谢,

1 个答案:

答案 0 :(得分:1)

只需使用表名和一个空数组立即初始化哈希:

def table_content_to_hash(table)
  hash = { table => [] }

  rows = @pg_conn.exec "SELECT * FROM #{table}";
  rows.each do |row|
    hash[table] << child
  end

  puts hash
end