Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get ActiveRecord MySQL Query result as a hash, not array

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?

like image 358
Solomon Avatar asked Apr 28 '14 22:04

Solomon


1 Answers

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.

like image 79
sebkkom Avatar answered Nov 02 '22 22:11

sebkkom