在 Rails 应用程序中解析 PostgreSQL 结果对象

Zub*_*Man 4 ruby postgresql ruby-on-rails

我正在编写一个需要快速处理数十万行数据的应用程序,因此我研究了使用 将原始 SQL 嵌套在我的 Ruby 代码中ActiveRecord::Base.connection.execute,它运行良好。但是,每当我运行它时,我都会得到以下对象:

#<PG::Result:0x007fe158ab18c8 status=PGRES_TUPLES_OK ntuples=0 nfields=1 cmd_tuples=0>
Run Code Online (Sandbox Code Playgroud)

我已经用谷歌搜索了,找不到将 PG 结果解析为真正有用的东西的方法。是否有任何内置的 PG 方法可以做到这一点,或者是一种解决方法,还是其他任何东西?

这是我正在使用的查询:

SELECT row_to_json(row(company_name, ccn_short_title, title))
FROM contents
WHERE contents.company_name = '#{company_name}'
AND contents.title = '#{title}';
Run Code Online (Sandbox Code Playgroud)

two*_*ves 6

实际上PG::Result响应了Enumerable模块中许多众所周知的方法。您可以将它们全部输出以观察所需的:

query = "SELECT row_to_json(row) from (select * from users) row"
result = ActiveRecord::Base.connection.execute(query)
result.methods - Object.methods
# => returns an array of methods which can be used
Run Code Online (Sandbox Code Playgroud)

例如,您可以迭代结果并将它们映射到更合适的东西......

result.map do |row|
  JSON.parse(row["row_to_json"])
end
# => returns familiar hashes
Run Code Online (Sandbox Code Playgroud)

通过其索引获取所需的结果哈希...

result[0]
Run Code Online (Sandbox Code Playgroud)

以及更多。