6

I am writing an app that needs to quickly process hundreds of thousands of rows of data, so I've looked into nesting raw SQL in my Ruby code using ActiveRecord::Base.connection.execute, which is working beautifully. However whenever I run it I get the following Object as a result:

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

I've googled around and can't find a way to parse the PG Result into something actually useful. Is there any built-in PG way to do this, or a workaround, or anything 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}';
1
  • Don't use raw SQL unless you absolutely can't avoid it. Writing raw SQL often ties you directly to a specific DBM which means portability and maintenance problems and negates the advantages of using an ORM. Commented Jun 9, 2015 at 23:38

1 Answer 1

8

Actually PG::Result responds to many well-known methods from Enumerable module. You can output them all to watch for the desired ones:

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

For example, you could iterate the results and map them to something more suitable...

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

Get a desired result hash by its index...

result[0]

And much more.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.