ruby - 如何使pg gem查询结果符号化?

标签 ruby postgresql

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

最佳答案

如果没有本地方式:

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) }

这也支持连接模型。

关于ruby - 如何使pg gem查询结果符号化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23601158/

相关文章:

ruby-on-rails - rails : Belongs_to and Has_many associations in Rails Engines

ruby - 处理 3 个或更多默认参数 Ruby

postgresql - kubernetes timescaledb statefulset : Changes lost on pod recreation

postgresql - 数据仓库的每小时报告

ruby - 创建新文件时在 emacs 中加载模板

ruby - 如何在 RSpec 模拟中使用动态值?

php - 如何像 SQL 中的括号一样用 eloquent 编写查询?

postgresql - 如果 Postgresql 中不存在则添加列

postgresql - SSL 错误 : point is not on curve with psycopg2 on Heroku

ruby - 在 Windows 8.1 中使用 gem 安装 sass 时出错