Parsing a PostgreSQL Result Object in a Rails Application

I am writing an application that should quickly process hundreds of thousands of rows of data, so I searched for the embedded raw SQL code in my Ruby code with help ActiveRecord::Base.connection.executethat works great. However, whenever I run it, I get the following object:

#<PG::Result:0x007fe158ab18c8 status=PGRES_TUPLES_OK ntuples=0 nfields=1 cmd_tuples=0>

I searched googled and can't find a way to parse the PG result into something really useful. Is there a built-in PG method for this or a workaround or something really?

Here is the query I'm using:

SELECT row_to_json(row(company_name, ccn_short_title, title))
FROM contents
WHERE contents.company_name = '#{company_name}'
AND contents.title = '#{title}';
+4
source share
1 answer

Actually PG::Resultanswers many well-known methods from the module Enumerable. You can print them all to look at the ones you need:

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

, - ...

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

...

result[0]

.

+3

All Articles