在mysql2 gem中,我们可以使用此语句使所有查询结果符号化
require 'mysql2'
Mysql2::Client.default_query_options.merge!(symbolize_keys: true)
DB = Mysql2::Client.new(host: "localhost", username: "benchmarkdbuser", password: 'benchmarkdbpass')
DB.select_db('hello_world')
res = DB.query "SELECT id, message FROM Fortune"
rows = res.map { |row| row }
# [{id: 1, message: 'bla'}] --> id and message are symbols, not strings
如何在pg gem上执行此操作?
require 'pg'
DB = PG::Connection.new('localhost',5432,nil,nil,'hello_world','benchmarkdbuser','benchmarkdbpass')
res = DB.query "SELECT id, message FROM Fortune"
rows = res.map { |row| row }
# [{"id" => 1, "message" => "bla"}] --> id and message are strings, not symbols
答案 0 :(得分:3)
如果没有本地方式:
h_to_sym = ->(row){ row.keys.each_with_object({}) { |k, o|
o[k.to_sym] = row[k].is_a?(Hash) ? h_to_sym.(row[k]) : row[k] }
}
p res.map.with_object([]) { |row, h| h << h_to_sym.(row) }
这也支持联合模型。