7

When running a mysql query with ActiveRecord with Class.connection.execute('query here'), the result is an array, as opposed to a hash in postgres. This is tested with both mysql and mysql2 adapters, even though the default for mysql2 is to return the query result as a hash.

How can I get ActiveRecord to change the configuration options on the connection to return query results as a hash? Can I just not use ActiveRecord for this and I should use the raw mysql2 client?

1

1 Answer 1

26

I had a similar problem and I found the solution on this answer:

You can do data = Class.connection.exec_query('query here') to get an ActiveRecord::Result

Then, you can do data.first for a hash, or use any of the other methods mentioned in the docs.

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

2 Comments

Thanks, it's exec_query that do the trick, I was testing with execute
@244an Glad this is still helpful! :)

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.